skip to Main Content

I’m practicing React by creating a CV form. I’ve create several input components that hold state (‘pending’, ‘submitted’, ‘editing’) so that they can be individually edited and saved without effecting the other components. However, I want the form itself, which would be the parent, to trigger the setState of all of the components to ‘submitted’ when the form is submitted. How do I do this?

I’m thinking I have to create some kind of callback function in the form component that is then sent down to the input component to trigger the setState function. But I’m not sure how to do that.

I’ve looked at lifting the state up instead, but I’m not sure how to make sure that each input component can still be left unaffected when I want to edit just one.

2

Answers


  1. then put the state in the parent component and then move the state and setState as props to the children.

    share the specific part of the code and I’d show you

    Login or Signup to reply.
  2. 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>
            )
        }
    
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search