reactjs – How to trigger setState in a child component from a parent component?


Elaborating on @Niv G’s suggestion with some code examples.

Since you haven’t shared any code samples to get an idea, I assume your form component looks like this.

class CVForm {

  render () {
    return (
      <form>
        <FieldOne />
        <FieldTwo />
      </form>
    )
  }
}

You can set the state of all components to submitted by lifting the state up passing it to the components as follows.

class CVForm {
  state = {
    fieldOneStatus: "",
    fieldTwoStatus: "",
  }
  
  // Set all components to `submitted` state on form submission. 
  handleSubmit () {
    this.setState({
      fieldOneStatus: "submitted",
      fieldTwoStatus: "submitted",
    })
  }

  render () {
    return (
      <form onSubmit={handleSubmit}>
        <FieldOne status={this.state.fieldOneStatus} />
        <FieldTwo status={this.state.fieldTwoStatus} />
      </form>
    )
  }
}

You would handle the status prop in each individual field as follows.

export class FieldOne {
   
    render () {
        return (
          <input></input>
          <p>Field status: {this.props.status}</p>
        )
    }

}



Source link

Leave a Comment