Reputation: 7801
I have been searching at lengths for an answer to this question, without success.
I would like to find the size of a React component, from another component. Is there another way to do it than the approaches I have listed below?
I will use the answer to dynamically get the height of my navbar from other components and hooks that need it.
Usecase examples
What I have tried
ref
to the navbar, then forwarding that around my entire application. That's a bit of a nightmare.id
to the navbar container, then finding it with vanilla js (getElementById). I understand from many other answers, that this is inferior to using a ref
.Upvotes: 1
Views: 872
Reputation: 2075
If you use the context API like @DBS is suggesting then you could store the element or its height in global state and grab it from any component.
Otherwise, if there are cases where the user will interact with the nav to initiate the scroll, then you could use the event
object to target the nav. This is vanilla JS, but the same concept applies in React:
function getHeight(event) {
const clickedElem = event.currentTarget
const nav = clickedElem.closest('#nav')
const navHeight = nav.offsetHeight
console.log(navHeight + 'px')
}
<div id="nav">
<button onclick="getHeight(event)">Click me</button>
</div>
Otherwise, I would totally go for document.querySelector('#navID')
. I don't think it's inferior at all. It just depends on the use case.
But if you really want to be inferior you could still use ref
and store the height value in the window
object on component mount, and then you can get it there from within any component:
useEffect(() => {
window.navHeight = nav.current.offsetHeight
}, [])
Upvotes: 1