0

I have a child component with a form. When a user submits the form I need to update the state in my top level component.

From reading the docs I belive the correct way is to create a function to update the state in the parent component, and then pass it down to the child component via props where it is executed.

In my child component:

  submit(e) {
    e.preventDefault();
    const setLength = parseInt(this.setLength.value.slice(0, -1));
    const restLength = parseInt(this.restLength.value.slice(0, -1));
    const noOfSets = parseInt(this.noOfSets.value);
    const noOfRounds = parseInt(this.noOfRounds.value);
    this.props.run(setLength, restLength, noOfSets, noOfRounds);
  }

In my parent component:

run(setLength, restLength, noOfSets, noOfRounds) {
    this.setState({
      setLength,
      restLength,
      noOfRounds,
      noOfSets,
      setTimeRemaining: setLength,
      restTimeRemaining: restLength,
      currentSet: 1,
      currentRound: 1,
      resting: false
    }, () => {
      this.updateProgress('running');
    });
  }

  render() {
    return (
      <Child run={this.run}/>

My code above works but seems very prone to bugs to me. If I change the order of setLength, restLength, noOfSets, noOfRounds in either function then the wrong values will be set. Should I therefore be passing an object with key value pairs? Or have I fundamentally gone about this the wrong way

Evanss
  • 23,390
  • 94
  • 282
  • 505
  • Have you bind the function like this.run.bind(this) ? – Vivek Doshi Nov 06 '17 at 05:39
  • This isn't a question about reactjs, but about using multiple parameters vs a single object parameter, for which there are already answers for. See [here](https://stackoverflow.com/questions/12826977/multiple-arguments-vs-options-object), for example. – chipit24 Nov 06 '17 at 05:39

0 Answers0