18

I am using two components and I am using this pattern: child component should stay isolated as much it can - it is handling its own validation error. Parent component should check for errors which have dependencies between children. So, in my case: password field and password confirmation field.

Here is my code:

a) SignUp (parent)

Setting initial state.

 constructor() {
     super();

     this.state = {
         isPasswordMatching: false
     };
 }

In render() method I am outputting my child component. Through prop called callback I am propagating method isPasswordMatching() by binding parent's this. The goal is that method can be called within child component.

<TextInput
    id={'password'}
    ref={(ref) => this.password = ref}
    callback={this.isPasswordMatching.bind(this)}
    // some other unimportant props
/>

<TextInput
    id={'passwordConfirm'}
    ref={(ref) => this.passwordConfirm = ref}
    ...

isPasswordMatching() method is checking if passwords match (through refs this.password and this.passwordConfirm) and then updates state. Please note that this method is called inside child (password or passwordConfirm).

isPasswordMatching() {
    this.setState({
        isPasswordMatching: this.password.state.value === this.passwordConfirm.state.value
    });
}

b) TextInput (child)

Setting initial state.

constructor() {
    super();

    this.state = {
        value: '',
        isValid: false
    };
}

On blur validation is done and state is updated.

onBlur(event) {

    // doing validation and preparing error messages

    this.setState({
        value: value,
        isValid: this.error === null
    });
}

Latest. Callback prop is called.

componentDidUpdate(prevProps) {
    if (prevProps.id === 'password' || prevProps.id === 'passwordConfirm') {
        prevProps.callback();
    }
}

Issue

Somehow my refs are lost. Scenario:

  1. Parent component is renderder
  2. Child components are rendered
  3. I am entering one of input fields and get out (this invokes onBlur() method) - state gets updated, child component is rendered
  4. componentDidUpdate() is invoked and prevProp.callback() as well
  5. When going to isPasswordMatching() method I am outputting this.password and this.passwordConfirm - they are objects with expected values of reference. Updating state of parent - component gets rendered.
  6. Then again all children are rendered, components get updated, callback is called but this time this.password and this.passwordConfirm are null.

I have no idea why references are kinda lost. Should I be doing something differently? Thank you in advance.

be-codified
  • 5,704
  • 18
  • 41
  • 65

2 Answers2

19

See the react documentation here, with important warnings and advise about when to use or not to use refs.

Note that when the referenced component is unmounted and whenever the ref changes, the old ref will be called with null as an argument. This prevents memory leaks in the case that the instance is stored, as in the second example. Also note that when writing refs with inline function expressions as in the examples here, React sees a different function object each time so on every update, ref will be called with null immediately before it's called with the component instance.

Galeel Bhasha
  • 1,877
  • 13
  • 19
  • 2
    Thank you for you effort. Oh, so this is my issue. Are you having any pointers how should I solve this? Should I use context? – be-codified Jul 16 '16 at 08:11
  • Thanks. This seems to have been lost in the documentation update. – Paul S Dec 20 '16 at 21:05
  • 2
    If you are rendering the `ref` element conditionally, you will need to use `style={{ display: 'none' }}` instead of simply not rendering it, otherwise the ref is not created. – Raine Revere Aug 26 '18 at 22:00
7

I'm not sure if this answers @be-codified's question for not, but I found this running into a similar issue. In my case, it turned out that it was due to using a functional component.

https://reactjs.org/docs/refs-and-the-dom.html#refs-and-functional-components

Refs and Functional Components You may not use the ref attribute on functional components because they don’t 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.
You can, however, use the ref attribute inside a functional component as long as you refer to a DOM element or a class component

The documentation explains what you should do to solve the issue if you have control of the component you're trying to render.

However in my case, the component was from a 3rd party library. So, simply wrapping the component worked fine.

Working

<div ref={element => this.elementName = element}>
    <FunctionalComponent />
</div>

Not Working
sets this.elementName to null

<FunctionalComponent ref={element => this.elementName = element} />

Hope this helps anyone finding this question like I did.

mawburn
  • 2,232
  • 4
  • 29
  • 48