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 object
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>
  )
                        Declare a reference using useRef hook and then read current.offsetHeight and current.offsetWidth properties. 
Here is the code:
import React, { useEffect, useRef } from 'react';
const PlantationMap = (props) => {
    const stageCanvasRef = useRef(null);
    // useEffect will run on stageCanvasRef value assignment
    useEffect( () => {
        // The 'current' property contains info of the reference:
        // align, title, ... , width, height, etc.
        if(stageCanvasRef.current){
            let height = stageCanvasRef.current.offsetHeight;
            let width  = stageCanvasRef.current.offsetWidth;
        }
    }, [stageCanvasRef]);
    return(
        <div className = "stage-canvas" ref = {stageCanvasRef}>
            <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>);
}
export default PlantationMap;
                        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