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()
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.
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.
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> ) } }
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>; };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With