Skip to content

Instantly share code, notes, and snippets.

@whoisryosuke
Created May 3, 2021 21:07
Show Gist options
  • Save whoisryosuke/06f91d7cbcaa76b969bb73576062bb83 to your computer and use it in GitHub Desktop.
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
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