React state management

From wikinotes
Revision as of 23:26, 10 December 2022 by Will (talk | contribs) (Created page with "HTML forms in react behave similarly to html,<br> but react encourages you to mirror form state changes within your react components so they can be the source-of-truth. = Documentation = <blockquote> {| class="wikitable" |- | official tutorial || https://reactjs.org/docs/forms.html |- |} </blockquote><!-- Documentation --> = Mirroring Form State = <blockquote> A <code>text</code> input maintains state in the browser when the user changes text.<br> It is encouraged to m...")
(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>
    );
  }
}