How to get the width of a react element

前端 未结 8 1193
灰色年华
灰色年华 2020-12-01 01:10

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 ha

8条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-01 01:45

    A simple and up to date solution is to use the React React useRef hook that stores a reference to the component/element, combined with a useEffect hook, which fires at component renders.

    import React, {useState, useEffect, useRef} from 'react';
    
    export default App = () => {
      const [width, setWidth] = useState(0);
      const elementRef = useRef(null);
    
      useEffect(() => {
        setWidth(elementRef.current.getBoundingClientRect().width);
      }, []); //empty dependency array so it only runs once at render
    
      return (
        
    {width}
    ) }

提交回复
热议问题