What's the proper way of passing a ref to a prop?

I’m trying to pass a ref of a component to another component. Since string refs are being deprecated I’m using callback refs.

So I have something similar to this:

<One ref={c => this.one = c}/>
<Two one={this.one}/>

The problem is that whenever I try to access this.props.one inside Two I get undefined.

I have even tried this on Two:

componentDidMount(){
    setTimeout(()=>{
        console.log(this.props.one);
    },5000)
}

It seems the problem is that when the prop is created, the ref doesn’t exist yet since it’s created once One is mounted. But I don’t know how to "refresh" the props on Two to get the ref to the mounted component.

So what’s the proper way of passing a ref to another component?

Edit

Some users have suggested to encapsulate that logic in a higher component, which in itself renders those other child components.

The problem with that approach is that you can’t create reusable logic and you have to repeat the same logic over and over in those encapsulating components.

Let’s say you want to create a generic <Form> component which encapsulates the submit logic to your store, error checking, etc. And you do something like this:

<Form>
    <Input/>
    <Input/>
    <Input/>
    <Input/>
    <SubmitButton/> 
</Form>

In this example <Form> can’t access the instances (and methods) of the children since this.props.children doesn’t return those instances. It returns some list of pseudo components.

So how can you check if a certain <Input/> has detected a validation error without passing a ref?

You have to encapsulate those components in another component with the validation logic. For example in <UserForm>. But since each form is different the same logic has to be copied in <CategoryForm>, <GoupForm>, etc. This is terribly inefficient which is why I want to encapsulate the validation logic in <Form> and pass references of the <Input> components to <Form>.

100 thoughts on “What's the proper way of passing a ref to a prop?”

Leave a Comment