Home > Enterprise >  React - Identify an element render (paint) completion
React - Identify an element render (paint) completion

Time:01-10

In angular, we can write a directive to identify whether any element is rendered or not.

In react, we can use *useEffect* for the component mount. But in reality, the element is not available in the dom. How to identify whether the dom completes the render. I need to calculate the position and height of an element. But cannot identify the render completes. Always gets zero for the height.

CodePudding user response:

Check out useLayoutEffect hook to access the DOM after rendering: https://beta.reactjs.org/reference/react/useLayoutEffect

useLayoutEffect(() => {
  const { height } = ref.current.getBoundingClientRect();
  setTooltipHeight(height);
}, []);

CodePudding user response:

you can use useRef to get html element when it will be rendered in DOM, after first render you can get width/height (elementRef.current?.offsetHeight).

CodePudding user response:

This is how I do it, using a ref:

const [divHeight, setDivHeight] = useState(0);

const handleRect = useCallback(node => {
  if (node !== null) {
    setDivHeight(Math.round(node.getBoundingClientRect().height));
  }
}, []);


// ...

return (
  <div ref={handleRect}>
    .....   
  </div>
)
  • Related