Santa Clauze
Santa Clauze

Reputation: 173

Mapping state of children to Parent array state

Description: My parent Component A has a state array such as:

state = { validatedSteps = [false, false, false] }

The state of A has for array length the exact same number of children, therefore, in this case, 3.

Each children have a state such as:

state = { validated = true }

Question: What is the best way for me to map the parent state array to reflect the state of each children?

Upvotes: 0

Views: 69

Answers (2)

Dev
Dev

Reputation: 3932

In each child component, when you change the state, you can notify the parent component and update the state of appropriate step. For example, I am assuming three components as , Step1, Step2, Step3.

In Parent component,

validateStep(step) {
  let stepsValidated = this.state.validatedSteps.slice();
  stepsValidated[step]=true
  this.setState({
    validatedSteps: stepsValidated
  })
}

<Step1 validate={this.validateStep}/>
<Step2 validate={this.validateStep}/>
<Step3 validate={this.validateStep}/>

In Child components, lets take Step1, you can pass the appropriate index as the parameter, something like this.

...
validate() {
  this.stateState({ validated:true }, 
  ()=> {
    this.props.validate(0);
  })
}
...

Upvotes: 2

salman.zare
salman.zare

Reputation: 649

If we change the stepsValidated[step]=true to the stepsValidated[step-1]=true , will be completely correct.

Upvotes: 1

Related Questions