search

Home  >  Q&A  >  body text

Retrieving the width of an element when using inline JSX rendering in a return statement

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粉441076405P粉441076405419 days ago697

reply all(1)I'll reply

  • P粉317679342

    P粉3176793422023-09-21 19:17:46

    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.

    reply
    0
  • Cancelreply