Step 18

We want to allow users to type in a word in the search bar. Therefore, let's update the Search component to allow changes to its state (i.e., the word property).

Update the <input> element and give it an onChange attribute as follows.

    <input
      className="input is-large is-fullwidth"
      id="define-input"
      placeholder="Enter a word"
      type="text"
      value={this.state.word}
+     onChange={this.changeWord}
    />

Let's define the changeWord method:

changeWord = (event) => {
  this.setState({word: event.target.value});
}

Visit the running app in the browser. Note how now we can type in a word in the search bar!

Notice the changeWord method uses this.setState to change the state. Normally, we would directly change the state:

changeWord = (event) => {
  this.state.word = event.target.value;
}

However, if you modify the state directly, React will not know about it! So instead, when you update the state, you must use the function setState (inherited from the React.Component class).

To use setState, we pass an object to it, and that object will be merged into the current state to form the new state.

changeWord = (event) => {
  this.setState({word: event.target.value});
}

The reason React requires you to use the setState method is for it to recognize when you have updated the state. React, in turn, will automatically make the necessary updates to the UI to reflect the updated state. This automatic UI rendering is one of the key benefits of using React to build user interfaces:

When it comes to re-rendering the UI, we only have to think about updating the state.

  • We don't have to keep track of exactly which parts of the UI changed each time there are updates.
  • We don't need to decide how we will efficiently re-render the UI.
  • React compares the previous state and the new state to determine what has changed and makes these decisions for us.
  • This process of determining what has changed in the previous and new states is called Reconciliation.