Created
May 3, 2021 21:07
-
-
Save whoisryosuke/06f91d7cbcaa76b969bb73576062bb83 to your computer and use it in GitHub Desktop.
ReactJS - Dynamically create Refs for children using useRef hook and createRef - @see: https://stackoverflow.com/questions/55995760/how-to-add-refs-dynamically-with-react-hooks
This file contains hidden or 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
const { | |
useState, | |
useRef, | |
createRef, | |
useEffect | |
} = React; | |
const data = [ | |
{ | |
text: "test1" | |
}, | |
{ | |
text: "test2" | |
} | |
]; | |
const Component = () => { | |
const [heights, setHeights] = useState([]); | |
const elementsRef = useRef(data.map(() => createRef())); | |
useEffect(() => { | |
const nextHeights = elementsRef.current.map( | |
ref => ref.current.getBoundingClientRect().height | |
); | |
setHeights(nextHeights); | |
}, []); | |
return ( | |
<div> | |
{data.map((item, index) => ( | |
<div ref={elementsRef.current[index]} key={index} className={`item item-${index}`}> | |
{`${item.text} - height(${heights[index]})`} | |
</div> | |
))} | |
</div> | |
); | |
}; | |
const rootElement = document.getElementById("root"); | |
ReactDOM.render(<Component />, rootElement); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment