0

I want to get the height after an element is rendered. The element is inside another component than which I want to detect it in.

I know I can do it like this:

  const heightOfStepper = document.getElementsByClassName(
    "step-indicator"
  )?.[0]?.offsetHeight;
  
  const minHeight = useMemo(
    () => `calc(${heightOfStepper}px + var(--small-spacing))`,
    [heightOfStepper]
  );

But when I console.log out the heightOfStepper, the value is 0 the first render, and if a add some code to my IntelliJ and save, then I get the real height of the stepper, since then the stepper is already mounted.

How can I get the height of an element after it has rendered, and the component is inside another component? (So I can not just use useEffect(() => ..., []))

RMT
  • 942
  • 2
  • 12
  • 32

1 Answers1

0

In react you should avoid regular DOM queries (like getElementsByClassName) - use ref instead. What do you mean you cannot use useEffect? You can use it even in deeply nested component. If you want to get height of parent element you will want to use forward ref, e.g. like this:

// parent component
const App = () => {
  const ref = useRef(null);
  return (
    <div ref={ref}>
      MyDiv
      <Child ref={ref} />
    </div>
  );
};

// child component
const Child = React.forwardRef((props, ref) => {
  useEffect(() => {
    console.log(ref.current.offsetHeight);
  }, []);
  return <p>I'm a child component</p>;
});

If your find yourself in need of passing ref deep through components tree or e.g. between siblings - pass ref through context - that was answered here

Emzaw
  • 618
  • 6
  • 11