I have this component:
function Div() {
return (
<div id="hello" ref={el => {
console.log(el.id) // <empty string>
}}/>
)
}
I’d like to access the element’s attributes in the ref
callback, but they all seem to have default values. I know I can do something hacky like this:
function Div() {
return (
<div id="hello" ref={el => {
setTimeout(() => {
console.log(el.id) // "hello"
})
}}/>
)
}
Any downsides to this? Is there a better way or is this the canonical way? Couldn’t find this behavior in the docs.
2
Answers
I don’t see any problem with the first approach, I tried your snippet here and it logged the
id
of thediv
.Maybe check how you are using
Div
for rendering.When a
ref
function is invoked the element is not inserted into the page yet, that is why any layout related values likewidth
,height
,position
are 0.If you need those values you need to access the element after it inserted into the DOM using an
onMount
hook which is guaranteed to run after the element is inserted into to the DOM.