Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the width of a react element

Tags:

reactjs

Im trying to create a range input that displays a tooltip right above the slider thumb.

I went through some vanilla JS examples online and it seems that I need to have the width of the element to acomplish that.

So I was just wondering how to get the elements width?

Pretty much the equivalent of the JQuery method $(element).width()

like image 418
Rick Enciso Avatar asked May 06 '17 05:05

Rick Enciso


People also ask

How do you give the width in React?

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. 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.

How do you get the width of an image in React?

To get the dimensions of image with React, we can get it from the load event handler of the image. We define the onImgLoad function that gets the image from the target property. Then we destructure the offsetHeight and offsetWidth properties from the image. Next, we log the height and width with console.


2 Answers

    class MyComponent extends Component {       constructor(props){         super(props)         this.myInput = React.createRef()       }        componentDidMount () {         console.log(this.myInput.current.offsetWidth)       }        render () {         return (         // new way - as of [email protected]         <div ref={this.myInput}>some elem</div>         // legacy way         // <div ref={(ref) => this.myInput = ref}>some elem</div>         )       }     } 
like image 54
Rick Enciso Avatar answered Oct 16 '22 08:10

Rick Enciso


With hooks:

const MyComponent = () => {   const ref = useRef(null);   useEffect(() => {     console.log('width', ref.current ? ref.current.offsetWidth : 0);   }, [ref.current]);   return <div ref={ref}>Hello</div>; }; 
like image 26
Nelu Avatar answered Oct 16 '22 08:10

Nelu