reactjsreduxref

React - How to pass `ref` from child to parent component?


I have a parent and a child component, I want to access the ref of an element which is in the child component, in my parent component. Can I pass it with props?

// Child Component (Dumb):
export default props =>
    <input type='number' ref='element' />

// Parent Component (Smart):
class Parent extends Component {
    constructor(props) {
        super(props);
    }

    componentDidMount() {
        const node = this.refs.element; // undefined
    }

    render() {
        return <Dumb { ...this.props }/>
    }
}

Solution

  • You could use the callback syntax for refs:

    // Dumb:
    export default props =>
        <input type='number' ref={props.setRef} />
    
    // Smart:
    class Parent extends Component {
        constructor(props) {
            super(props);
        }
    
        setRef(ref) {
            this.inputRef = ref;
        }
    
        render(){
            return <Dumb {...this.props} setRef={this.setRef} />
        }
    }