How To Get The Width Of An Element In React

Get the Width of an Element in React

Knowing how to get the width of an element in React will make it easier for you to manipulate your element. How will you do? Let’s go into detail.

Get the width of an element in React

Use element.clientWidth

Syntax:

element.clientWidth

The element.clientWidth will return the width of an element in pixels including padding but no borders, margins, or vertical scrollbars. To use this method, firstly, we will have to catch the element you want to get the width. We can do that with the useRef hook. With the useRef hook, you can refer to an element created by JSX and store it in a variable through the ‘current’ property.

Example:

import { useEffect, useRef, useState } from 'react';
import './App.css';
 
function App() {
    const h1Ele = useRef();
    const block1 = useRef();
    const block2 = useRef();
    const [h1Width, seth1Width] = useState();
    const [block1Width, setblock1] = useState();
    const [block2Width, setblock2] = useState();
  
    useEffect(() => {
        seth1Width(h1Ele.current.clientWidth);
        setblock1(block1.current.clientWidth);
        setblock2(block2.current.clientWidth);
    }, []);
  
    return (
        <div className="App">
            <h1 ref={h1Ele}>Hello From Learn Share IT</h1>
            <h1>H1 width: {h1Width}</h1>
            <hr/>
            <div ref={block1} style={{width: '100px', height: '100px', backgroundColor: 'black'}}>
              	<span style={{lineHeight: '100px', color: 'white'}}>I like React</span>
        	</div>
            <p/>
            <span>Paragraph 1 width: {block1Width}</span>
            <hr/>
            <span style={{display: 'block', width: '500px', backgroundColor: 'green', color: 'white'}} ref={block2}>Lorem ipsum dolor sit, amet consectetur adipisicing elit. Facere perferendis dicta ex eum eaque deserunt dolorem. Ullam, dolores corrupti voluptatum repellat porro vitae est ea officiis similique non, atque distinctio?</span>
            <p/>
            <span>Paragraph 2 width: {block2Width}</span>
        </div>
    )
}
 
export default App;

Output:

I get the element’s width with element.clientWidth inside useEffect hook with empty array dependencies, meaning it only runs once when React renders. Here notice that width 100 and width 500 are what I set to ‘block1’ and ‘block2’.

Use element.getBoundingClientRect()

Syntax:

element.getBoundingClientRect()

The element.getBoundingClientRect() will return a DOMRect to give you information about the size and position of your element. It looks like this:

So we can apply it to the code above.

Example:

import { useEffect, useRef, useState } from 'react';
import './App.css';
 
function App() {
    const h1Ele = useRef();
    const block1 = useRef();
    const block2 = useRef();
    const [h1Width, seth1Width] = useState();
    const [block1Width, setblock1] = useState();
    const [block2Width, setblock2] = useState();
  
    useEffect(() => {
        seth1Width(h1Ele.current.getBoundingClientRect().width);
        setblock1(block1.current.getBoundingClientRect().width);
        setblock2(block2.current.getBoundingClientRect().width);
    }, []);
  
    return (
        <div className="App">
            <h1 ref={h1Ele}>Hello From Learn Share IT</h1>
            <h1>H1 width: {h1Width}</h1>
            <hr/>
            <div ref={block1} style={{width: '100px', height: '100px', backgroundColor: 'black'}}>
              	<span style={{lineHeight: '100px', color: 'white'}}>I like React</span>
        	</div>
            <p/>
            <span>Paragraph 1 width: {block1Width}</span>
            <hr/>
            <span style={{display: 'block' , width: '500px',backgroundColor: 'green', color: 'white'}} ref={block2}>Lorem ipsum dolor sit, amet consectetur adipisicing elit. Facere perferendis dicta ex eum eaque deserunt dolorem. Ullam, dolores corrupti voluptatum repellat porro vitae est ea officiis similique non, atque distinctio?</span>
            <p/>
            <span>Paragraph 2 width: {block2Width}</span>
        </div>
    )
}
 
export default App;

Output:

You can see here with the apparent width that I set, ‘block1’ and ‘block2’ still have a width is 100, 500. But with H1 width, it is not a fixed size and does not have element.clientWidth to round the number. The element.getBoundingClientRect() method gives more exactly size of H1 element.

Summary

In this tutorial, I have explained how to get the width of an element in React. You can use element.clientWidth or element.getBoundingClientRect() method depending on your purpose. If you have any problems, please comment below. Thank you for reading!

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *