import React, { useRef } from 'react'
import EqualHeight from './EqualHeight'
const items = [
"Ullamco dolore aliqua excepteur exercitation est tempor anim fugiat esse veniam exercitation officia",
"Mollit laborum sunt anim",
"Consequat cillum et Lorem consectetur nostrud Lorem cupidatat ut dolor exercitation velit anim",
"Ea nisi enim ex minim cupidatat excepteur sint consectetur ut elit irure id dolore"
]
const MatchingHeightComponent = () => {
const refList = [
useRef(null),
useRef(null),
useRef(null),
useRef(null)
]
}
return (
<EqualHeight nodes={refList}>
{
items.map((text, index) => (
<div ref={refList[index]}>{data}</div>
))
}
</EqualHeight>
)
}
Created
May 28, 2019 22:23
-
-
Save krambuhl/150a116d7b9ed99f88b3afae0bc567d9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useEffect } from "react" | |
import debounce from "lodash.debounce" | |
const EqualHeight = ({ nodes, children }) => { | |
const handleResize = debounce(() => { | |
const currentNodes = nodes.map(node => node.current).filter(a => a) | |
const dimensionsList = currentNodes.map(node => { | |
// remove any forced sizing information | |
node.style.height = 'auto' | |
node.style.maxHeight = '' | |
node.style.minHeight = '' | |
// get natural size | |
const { top, height } = node.getBoundingClientRect() | |
return { node, top, height } | |
}) | |
// group nodes by top offset | |
const nodeGroups = Object.values( | |
dimensionsList.reduce((accumulator, { node, top, height }) => { | |
if (!accumulator[top]) accumulator[top] = [] | |
accumulator[top].push({ node, height }) | |
return accumulator | |
}, { }) | |
) | |
// get max height and update height for each group | |
nodeGroups.forEach((group) => { | |
const heightList = group.map(item => item.height) | |
const maxHeight = Math.max(...heightList) | |
// update height using the max height | |
group.forEach(({ node }) => { | |
node.style.height = `${maxHeight}px`; | |
}) | |
}) | |
}, 50) | |
useEffect(() => { | |
window.addEventListener('resize', handleResize); | |
return () => { | |
window.removeEventListener('resize', handleResize); | |
} | |
}) | |
// init | |
setTimeout(handleResize) | |
return ( | |
<React.Fragment> | |
{children} | |
</React.Fragment> | |
) | |
} | |
export default EqualHeight |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment