Search code examples
reactjs

How to get the width of a react element


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()


Solution

  • Use this solution if all you need is exactly the title of this question: the width of a react element.

    Complementing on Christopher's comment: You can use the 'react-use' library to do this. It also listens when the browser resizes. For reference: https://github.com/streamich/react-use/blob/master/docs/useMeasure.md

    import React from 'react';
    
    import { useMeasure } from 'react-use'; // or just 'react-use-measure'
    
    const sampleView = () => {
     const [ref, { width }] = useMeasure<HTMLDivElement>();
     console.log('Current width of element', width);
     return <div ref={ref}></div>;
    };
    
    export default sampleView;