Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 object

like image 575
Otavio Bonder Avatar asked Oct 03 '19 15:10

Otavio Bonder


2 Answers

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>
  )
like image 165
Bruce Smith Avatar answered Oct 09 '22 16:10

Bruce Smith


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;
like image 14
Erik Martín Jordán Avatar answered Oct 09 '22 17:10

Erik Martín Jordán