I have an image and I want to store its dimensions, for placing icons depending of the dimensions. I do so with useRef() hook.
const componentRef=useRef()
Then I add this componentRef to the <img ref={componentRef}>. For rendering the icons, I call a function {setIcons}.
return(
<div>
<img ref={componentRef}/>
{setIcons}
</div>
)
This function again looks like this.
const setIcons=(
props.positions_Reader.map((mac,i)=>(
<Icon
style={{
position:"absolute",
left:componentRef.current.getBoundingClientRect().x,
top:componentRef.current.getBoundingClientRect().y
}}
/>
))
)
The error occurs in this line left:componentRef.current.getBoundingClientRect().x
At the first render there is no error, but when I go back and open the component again, this error occurs. Are there any suggestions?
The problem is that you are trying to use componentRef before it is actually being assigned. Make use of useEffect and store the styles in state, this will ensure the re-render when componentRef.current changes
function App() {
const componentRef = React.useRef();
const [style, setStyle] = React.useState({})
useEffect(() => {
setStyle({
left: componentRef.current.getBoundingClientRect().x,
top: componentRef.current.getBoundingClientRect().y
})
}, [componentRef.current])
const setIcons = props.positions_Reader.map((mac, i) => (
<Icon
style={{
position: "absolute",
top: style.top + mac.x,
left: style.left + mac.y
}}
/>
));
return (
<div>
<img ref={componentRef} />
{setIcons}
</div>
);
}
Sample Demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With