Sometimes, we want to get the width of an element in a React component.
In this article, we’ll look at how to get the width of an element in a React component.
Get the Width of an Element in a React Component
To get the width of an element in a React component, we can assign a ref to the element we want to get the width of.
Then we can use the offsetWidth
property to get the width.
For instance, we can write:
import React, { useEffect, useRef } from "react";
export default function App() {
const ref = useRef(null);
useEffect(() => {
console.log("width", ref.current.offsetWidth);
}, []);
return <div ref={ref}>Hello</div>;
}
to add the ref
with the useRef
hook.
Then we pass ref
as the value of the ref
prop to assign the ref to the div.
And then we get the width of the div with the offsetWidth
property.
Conclusion
To get the width of an element in a React component, we can assign a ref to the element we want to get the width of.