Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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 }/>
    }
}
like image 345
Nick1R1 Avatar asked Mar 23 '17 15:03

Nick1R1


People also ask

How do you pass child ref to parent in react?

You may not use the ref attribute on functional components because they don't have instances. You should convert the component to a class if you need a ref to it, just like you do when you need lifecycle methods or state. So i think, if you want to use the ref , you need to use class .

Can you pass ref to component?

You can pass callback refs between components like you can with object refs that were created with React. createRef() . In the example above, Parent passes its ref callback as an inputRef prop to the CustomTextInput , and the CustomTextInput passes the same function as a special ref attribute to the <input> .

How do you get ref of child component react?

In child component, we create Refs by using React. createRef() and then attached to React elements via the ref attribute. // EXPLANATION: a reference to the node becomes accessible at the current attribute of the ref. In the parent component, we can get a reference to the Input component and call its focus() method.

Can we pass ref as props?

Regular function or class components don't receive the ref argument, and ref is not available in props either. Ref forwarding is not limited to DOM components. You can forward refs to class component instances, too.


1 Answers

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} />
    }
}
like image 179
TimoStaudinger Avatar answered Sep 21 '22 10:09

TimoStaudinger