10 React Challenges for Beginners - Lesson #4

React Challenge: Use React State to Update the DOM

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.

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

Fork this CodeSandbox to get started.

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

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

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

jsx
// Import React and useState
import { 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.

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

jsx
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.

<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:

jsx
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.

jsx
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

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.

Want to improve your coding and design skills?

I'm continually researching the best practices and tools for coding.
Join 50,000+ developers looking to make cool stuff.

We value your privacy. 1-click unsubscribe.

Chris Sev

Chris Sev

Chris Sev is the co-founder of Better Dev. Coding better every day. Previously he created Scotch.io which was acquired.

Comments

What did you think of the article? Let us know!
(these comments are powered by GitHub issues and use 0 trackers)