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:
- Parent component is renderder
- Child components are rendered
- I am entering one of input fields and get out (this invokes
onBlur()
method) - state gets updated, child component is rendered componentDidUpdate()
is invoked andprevProp.callback()
as well- When going to
isPasswordMatching()
method I am outputtingthis.password
andthis.passwordConfirm
- they are objects with expected values of reference. Updating state of parent - component gets rendered. - Then again all children are rendered, components get updated, callback is called but this time
this.password
andthis.passwordConfirm
arenull
.
I have no idea why references are kinda lost. Should I be doing something differently? Thank you in advance.