10 Days of React Challenges (Beginner): Use React State to Update the DOM

Publikováno: 10.5.2019

A common theme in modern front-end JavaScript libraries/frameworks is that they can help you manage the data in your applications.

Once you update something, React can immediate...

Celý článek

A common theme in modern front-end JavaScript libraries/frameworks is that they can help you manage the data in your applications.

Once you update something, React can immediately update the UI.

React uses a concept called state to keep data and update our UIs.

The Challenge: Update Data from Form Input

In this React challenge, we'll update data using an <input> field.

The main tasks are:

  • Use an <input> field to accept text
  • Update your UI based on that input field
  • Use React state to automatically update your UI
  • Update data using a form

Starter Code

Fork this CodeSandbox to get started: https://codesandbox.io/s/2x73k4o38n

The base CodeSandbox is styled using Bulma classes and basic CSS. Here's what the final page looks like:

Fork this CodeSandbox to get started: https://codesandbox.io/s/2x73k4o38n

Solution: Update Data from an Input

TODO: Video Here

With state in React, various parts of an application can be updated with data from other parts. In React 16.8, Hooks was introduced, which provided a way to use features of React class component features in functional components.

State provides a way to create and update dynamic data in an application.

In this challenge, we utilize the useState() hook to create and update state variables.

This challenge is completed in three steps:

  • Create state variables with default data
  • Pass the variables to the page
  • Create a form to handle the updating of the state data

Create State Variables

For this challenge, you require two state variables to hold name and age. Create them using the useState() hook in the App() component with:

// Import React and useState
import React, { useState } from "react";
// import other dependencies

function App() {
    // Create state variables here
  const [name, setName] = useState("Chuloo");
  const [age, setAge] = useState("38");

  return (
    <div className="App">

      // Content goes in here

    </div>
  );
}

Here, we created two variables name and age then assigned them default values of Chuloo and 38 respectively. The setName and setAge methods, update the state data when called and passed a new data value as a parameter.

Pass the Variables to the Page

In the returned JSX with a class of input-display we shall display the value of the state variables. Do this with:

function App() {
  const [name, setName] = useState("Chuloo");
  const [age, setAge] = useState("38");

  return (
    <div className="App">
      <div>
        <h2 className="subtitle is-4">Update Data from an input</h2>
      </div>

            // Display data from state
      <div className="input-display">
        <h3>Display Name: {name}</h3>
        <h3>Display Age: {age}</h3>
      </div>

    </div>
  );
}

We currently have the data from state displayed. The default values are on display until we alter them.

Handle Update of the State data

<input> elements in React are "controlled components" in that the value of the input is determined and updated using state. With this in mind, we shall update the value of the input to be that of its corresponding state data.

Also, when the value of the input element changes, its corresponding state data updates. This makes the state variable the single source of truth, as it controls the input element and its value.

Assign the name input's value and handle any change using the onChange attribute in App() with:

function App() {
  const [name, setName] = useState("Chuloo");
  const [age, setAge] = useState("38");

  return (
    <div className="App">

            // Display form data

      <div className="inputs">

                // Name input
        <div className="field">
          <label className="label">Name: </label>
          <input
            className="input"
            type="text"
            value={name}
            placeholder="William"
            onChange={e => setName(e.target.value)}
          />
        </div>

        // Handle Age input

      </div>
    </div>
  );
}

Do the same for age.

function App() {
  const [name, setName] = useState("Chuloo");
  const [age, setAge] = useState("38");

  return (
    <div className="App">

            // Form data display

      <div className="inputs">
        // Name input . . .

                // Age input
        <div className="field">
          <label className="label">Age: </label>
          <input
            type="number"
            className="input"
            placeholder="38"
            value={age}
            onChange={e => setAge(e.target.value)}
          />
        </div>
      </div>
    </div>
  );
}

Using the onChange event attribute, we call a function which updates the state variable with the current input data.

Here's what the final page looks like:

Completed CodeSandbox Version: https://codesandbox.io/s/9451yr9lrw

Conclusion

On completing this challenge, we have learned to use and update data from state. React can handle updating the DOM for us once we update state using Hooks.

Got questions, suggestions, and comments? We'd love to see them in the comment section. You can find other challenges here and join the live streams here. Happy keyboard slapping!

Nahoru
Tento web používá k poskytování služeb a analýze návštěvnosti soubory cookie. Používáním tohoto webu s tímto souhlasíte. Další informace