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

Nick1R1 picture Nick1R1 · Mar 23, 2017 · Viewed 26.3k times · Source

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 }/>
    }
}

Answer

Timo picture Timo · Mar 23, 2017

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} />
    }
}