Home > Back-end >  How do I forward a ref down to a child component?
How do I forward a ref down to a child component?

Time:08-20

The react documentation provides a way for a parent component to get the ref from a child component using the forwardRef method. But, I need to get the width of a parent component in a child component. Is there a way to forward a parent's ref in the child component?

CodePudding user response:

You could just access the ref in parent, make appropriate calculations and send down the props (width in your case) to the child.

<ChildComp parentWidth={ref.current && calc_for_ref} />

CodePudding user response:

If you want to get parent width from the child, you need to observe the parentRef prop with a useEffect, because the child will be rendered before the parent

const Child = (props) => {
    const {parentRef} = props

    const [parentWidth, setParentWidth] = React.useState(props.parentRef.current ? props.parentRef.current.clientWidth : 0)
    React.useEffect(() => {
      if (!!props.parentRef.current.clientWidth) {
        setParentWidth(props.parentRef.current.clientWidth)
      }
    }, [props.parentRef.current])

    return <div>The parent width is {parentWidth}</div>
}


const Parent = () => {
    const ref = React.useRef(null)

    const style = {
      border: "solid 1px black",
      width: "234px",
    }

    return (<div ref={ref} style={style}>
      Parent component
      <Child parentRef={ref} />
    </div>)
}


ReactDOM.render(<Parent />, document.getElementById("root"));
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.development.js"></script>

  • Related