Skip to content

Instantly share code, notes, and snippets.

@Uvacoder
Forked from whoisryosuke/dynamic-refs.jsx
Created October 18, 2022 16:11
Show Gist options
  • Select an option

  • Save Uvacoder/bf8a826ff801a88a0a78df12daa8df5e to your computer and use it in GitHub Desktop.

Select an option

Save Uvacoder/bf8a826ff801a88a0a78df12daa8df5e 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