React state management

From wikinotes
Revision as of 23:55, 10 December 2022 by Will (talk | contribs) (Will moved page React forms to React state management without leaving a redirect)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

HTML forms in react behave similarly to html,
but react encourages you to mirror form state changes within your react components so they can be the source-of-truth.

Documentation

official tutorial https://reactjs.org/docs/forms.html

Mirroring Form State

A text input maintains state in the browser when the user changes text.
It is encouraged to mirror this within your react component, to ensure your state matches what is rendered to screen.

// copied from official tutorial
class NameForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {value: ''};

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleChange(event) {
    this.setState({value: event.target.value});
  }

  handleSubmit(event) {
    alert('A name was submitted: ' + this.state.value);
    event.preventDefault();
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <label>
          Name: <input type="text" value={this.state.value} onChange={this.handleChange} />
        </label>

        <input type="submit" value="Submit" />
      </form>
    );
  }
}

Lifting State Up

The previous approach becomes especially useful if one component refers to state from multiple child components.
Using this approach to manage the render ensures that your changes are always synchronized within your parent-component's state.
see https://reactjs.org/docs/lifting-state-up.html

Since events travel downwards, your intercepting of the rendering (and passing state as params),
ensures the rendered state always updates all involved components together,
ensuring your state is always consistent.

// copied form official tutorial
class Calculator extends React.Component {
  constructor(props) {
    super(props);
    this.handleCelsiusChange = this.handleCelsiusChange.bind(this);
    this.handleFahrenheitChange = this.handleFahrenheitChange.bind(this);
    this.state = {temperature: '', unit: 'c'};
  }

  // changes to unit change the rendered `BoilingVerdict`
  // we want to make sure both 'unit' and 'temperature' are updated together
  handleCelsiusChange(temperature) {
    this.setState({unit: 'c', temperature});
  }

  handleFahrenheitChange(temperature) {
    this.setState({unit: 'f', temperature});
  }

  render() {
    const unit = this.state.unit;
    const temperature = this.state.temperature;
    const celsius = unit === 'f' ? tryConvert(temperature, toCelsius) : temperature;
    const fahrenheit = unit === 'c' ? tryConvert(temperature, toFahrenheit) : temperature;

    return (
      <div>
        <TemperatureInput
          unit="c"
          temperature={celsius}
          onTemperatureChange={this.handleCelsiusChange} />
        <TemperatureInput
          unit="f"
          temperature={fahrenheit}
          onTemperatureChange={this.handleFahrenheitChange} />
        <BoilingVerdict
          celsius={parseFloat(celsius)} />
      </div>
    );
  }
}