Retrieving the width of an element when using inline JSX rendering in a return statement
P粉441076405
P粉441076405 2023-09-20 22:00:52
0
1
732

I have an element and I want to calculate its width and then iterate how many times it takes to at least fill the width of the viewport.

The problem is, I can't get the width via the inline JSX render style I'm using. Even if I set it as a dependency, I still get the refWidth is empty error in useEffect.

Is there a way to calculate and render correctly without first adding the element to the return statement, getting its width, and then appending the required number of elements?

CodeSandbox link here

P粉441076405
P粉441076405

reply all(1)
P粉317679342

To access the width of an element in inline JSX rendering, you can use the useLayoutEffect hook.

import { useLayoutEffect, useRef, useState } from "react";

export default function App() {
  const windowWidth = 1920;
  const ref = useRef(null);
  const [numberOfItems, setNumberOfItems] = useState(0);

  useLayoutEffect(() => {
    ref.current && setNumberOfItems(Math.ceil(windowWidth / ref.current.clientWidth));
  }, [windowWidth]);

  return (
    <div className="App">
      <h2 ref={ref}>hello</h2>
      {Array.from({ length: numberOfItems }, (_, i) => (
        <h2 key={i}>
          hello
        </h2>
      ))}
    </div>
  );
}

useLayoutEffect hook ensures that width calculations are done after the element is rendered, resulting in more accurate results.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template