How to get the width of a react element

前端 未结 8 1250
灰色年华
灰色年华 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 02:00

    This is basically Marco Antônio's answer for a React custom hook, but modified to set the dimensions initially and not only after a resize.

    export const useContainerDimensions = myRef => {
      const getDimensions = () => ({
        width: myRef.current.offsetWidth,
        height: myRef.current.offsetHeight
      })
    
      const [dimensions, setDimensions] = useState({ width: 0, height: 0 })
    
      useEffect(() => {
        const handleResize = () => {
          setDimensions(getDimensions())
        }
    
        if (myRef.current) {
          setDimensions(getDimensions())
        }
    
        window.addEventListener("resize", handleResize)
    
        return () => {
          window.removeEventListener("resize", handleResize)
        }
      }, [myRef])
    
      return dimensions;
    };
    

    Used in the same way:

    const MyComponent = () => {
      const componentRef = useRef()
      const { width, height } = useContainerDimensions(componentRef)
    
      return (
        

    width: {width}px

    height: {height}px

    ) }

提交回复
热议问题