How to get parent width/height in React using Hooks?
I'm creating a component and I need to get it's parent <div>
width and height. I'm using Hooks, so all my components are functions. I've read some examples using classes, but this won't apply to my component.
So I have this component:
export default function PlantationMap(props) {
<div className="stage-canvas">
<Stage
width={window.innerWidth * 0.5}
height={window.innerHeight * 0.5}
onWheel={handleWheel}
scaleX={stage.stageScale}
scaleY={stage.stageScale}
x={stage.stageX}
y={stage.stageY}
draggable
/ >
</div>
}
How could I get the <div>
height and width to use in <Stage width={} height={} />
?
Thank you very much in advance
Edit: I tried using the useRef()
hook, like this:
const div = useRef();
return (
<div ref={div}>
...
</div>
)
But I can't access the div.current
objectjavascriptreactjsShareImprove this questionFollowedited Oct 3, 2019 at 15:16asked Oct 3, 2019 at 15:08

Otavio Bonder1,41922 gold badges1212 silver badges2727 bronze badges
- Why you don't use css in separate file/class and apply it here to follow separation of concerns? Its can be easier for you to mainening your code. – Qui-Gon Jinn Oct 3, 2019 at 15:26
- Because it's responsive. So I want to get the current width and height of the mounted component – Otavio Bonder Oct 3, 2019 at 15:28Add a comment
5 AnswersSorted by: Highest score (default) Date modified (newest first) Date created (oldest first) 20
I think useCallback is what you want to use so you can get the width and height when it changes.
const [height, setHeight] = useState(null);
const [width, setWidth] = useState(null);
const div = useCallback(node => {
if (node !== null) {
setHeight(node.getBoundingClientRect().height);
setWidth(node.getBoundingClientRect().width);
}
}, []);
return (
<div ref={div}>
...
</div>
)