How to get the width of a react element

前端 未结 8 1101
灰色年华
灰色年华 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
        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 React@16.3
            <div ref={this.myInput}>some elem</div>
            // legacy way
            // <div ref={(ref) => this.myInput = ref}>some elem</div>
            )
          }
        }
    
    0 讨论(0)
  • 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 (
        <div ref={componentRef}>
          <p>width: {width}px</p>
          <p>height: {height}px</p>
        <div/>
      )
    }
    
    0 讨论(0)
提交回复
热议问题