How to get parent width/height in React using Hooks?

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>
  )

Leave a Comment

tech