Reacting to Input with State·续

export default function Picture() {
  return (
    <div className="background background--active">
      <img
        className="picture"
        alt="Rainbow houses in Kampung Pelangi, Indonesia"
        src="/uploads/projects/react-dev-guide/202611/18e72a88bf7f067a.jpeg"
      />
    </div>
  );
}
body { margin: 0; padding: 0; height: 250px; }

.background {
  width: 100vw;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background: #eee;
}

.background--active {
  background: #a6b5ff;
}

.picture {
  width: 200px;
  height: 200px;
  border-radius: 10px;
  border: 5px solid transparent;
}

.picture--active {
  border: 5px solid #a6b5ff;
}

This component has two visual states: when the image is active, and when the image is inactive:

  • When the image is active, the CSS classes are background and picture picture--active.
  • When the image is inactive, the CSS classes are background background--active and picture.

A single boolean state variable is enough to remember whether the image is active. The original task was to remove or add CSS classes. However, in React you need to describe what you want to see rather than manipulate the UI elements. So you need to calculate both CSS classes based on the current state. You also need to stop the propagation so that clicking the image doesn't register as a click on the background.

Verify that this version works by clicking the image and then outside of it:

import { useState } from 'react';

export default function Picture() {
  const [isActive, setIsActive] = useState(false);

let backgroundClassName = 'background';
  let pictureClassName = 'picture';
  if (isActive) {
    pictureClassName += ' picture--active';
  } else {
    backgroundClassName += ' background--active';
  }

return (
    <div
      className={backgroundClassName}
      onClick={() => setIsActive(false)}
    >
      <img
        onClick={e => {
          e.stopPropagation();
          setIsActive(true);
        }}
        className={pictureClassName}
        alt="Rainbow houses in Kampung Pelangi, Indonesia"
        src="/uploads/projects/react-dev-guide/202611/18e72a88bf7f067a.jpeg"
      />
    </div>
  );
}
body { margin: 0; padding: 0; height: 250px; }

.background {
  width: 100vw;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background: #eee;
}

.background--active {
  background: #a6b5ff;
}

.picture {
  width: 200px;
  height: 200px;
  border-radius: 10px;
  border: 5px solid transparent;
}

.picture--active {
  border: 5px solid #a6b5ff;
}

Alternatively, you could return two separate chunks of JSX:

import { useState } from 'react';

export default function Picture() {
  const [isActive, setIsActive] = useState(false);
  if (isActive) {
    return (
      <div
        className="background"
        onClick={() => setIsActive(false)}
      >
        <img
          className="picture picture--active"
          alt="Rainbow houses in Kampung Pelangi, Indonesia"
          src="/uploads/projects/react-dev-guide/202611/18e72a88bf7f067a.jpeg"
          onClick={e => e.stopPropagation()}
        />
      </div>
    );
  }
  return (
    <div className="background background--active">
      <img
        className="picture"
        alt="Rainbow houses in Kampung Pelangi, Indonesia"
        src="/uploads/projects/react-dev-guide/202611/18e72a88bf7f067a.jpeg"
        onClick={() => setIsActive(true)}
      />
    </div>
  );
}
body { margin: 0; padding: 0; height: 250px; }

.background {
  width: 100vw;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background: #eee;
}

.background--active {
  background: #a6b5ff;
}

.picture {
  width: 200px;
  height: 200px;
  border-radius: 10px;
  border: 5px solid transparent;
}

.picture--active {
  border: 5px solid #a6b5ff;
}

Keep in mind that if two different JSX chunks describe the same tree, their nesting (first <div> → first <img>) has to line up. Otherwise, toggling isActive would recreate the whole tree below and reset its state. This is why, if a similar JSX tree gets returned in both cases, it is better to write them as a single piece of JSX.

Profile editor

Here is a small form implemented with plain JavaScript and DOM. Play with it to understand its behavior:

```js src/index.js active function handleFormSubmit(e) { e.preventDefault(); if (editButton.textContent === 'Edit Profile') { editButton.textContent = 'Save Profile'; hide(firstNameText); hide(lastNameText); show(firstNameInput); show(lastNameInput); } else { editButton.textContent = 'Edit Profile'; hide(firstNameInput); hide(lastNameInput); show(firstNameText); show(lastNameText); } }

function handleFirstNameChange() { firstNameText.textContent = firstNameInput.value; helloText.textContent = ( 'Hello ' + firstNameInput.value + ' ' + lastNameInput.value + '!' ); }

function handleLastNameChange() { lastNameText.textContent = lastNameInput.value; helloText.textContent = ( 'Hello ' + firstNameInput.value + ' ' + lastNameInput.value + '!' ); }

function hide(el) { el.style.display = 'none'; }

function show(el) { el.style.display = ''; }

let form = document.getElementById('form'); let editButton = document.getElementById('editButton'); let firstNameInput = document.getElementById('firstNameInput'); let firstNameText = document.getElementById('firstNameText'); let lastNameInput = document.getElementById('lastNameInput'); let lastNameText = document.getElementById('lastNameText'); let helloText = document.getElementById('helloText'); form.onsubmit = handleFormSubmit; firstNameInput.oninput = handleFirstNameChange; lastNameInput.oninput = handleLastNameChange;


```js sandbox.config.json hidden
{
  "hardReloadOnChange": true
}

```html public/index.html

Hello, Jane Jacobs!


This form switches between two modes: in the editing mode, you see the inputs, and in the viewing mode, you only see the result. The button label changes between "Edit" and "Save" depending on the mode you're in. When you change the inputs, the welcome message at the bottom updates in real time.

Your task is to reimplement it in React in the sandbox below. For your convenience, the markup was already converted to JSX, but you'll need to make it show and hide the inputs like the original does.

Make sure that it updates the text at the bottom, too!

```js
export default function EditProfile() {
  return (
    <form>
      <label>
        First name:{' '}
        <b>Jane</b>
        <input />
      </label>
      <label>
        Last name:{' '}
        <b>Jacobs</b>
        <input />
      </label>
      <button type="submit">
        Edit Profile
      </button>
      <p><i>Hello, Jane Jacobs!</i></p>
    </form>
  );
}
label { display: block; margin-bottom: 20px; }

You will need two state variables to hold the input values: firstName and lastName. You're also going to need an isEditing state variable that holds whether to display the inputs or not. You should not need a fullName variable because the full name can always be calculated from the firstName and the lastName.

Finally, you should use conditional rendering to show or hide the inputs depending on isEditing.

import { useState } from 'react';

export default function EditProfile() {
  const [isEditing, setIsEditing] = useState(false);
  const [firstName, setFirstName] = useState('Jane');
  const [lastName, setLastName] = useState('Jacobs');

return (
    <form onSubmit={e => {
      e.preventDefault();
      setIsEditing(!isEditing);
    }}>
      <label>
        First name:{' '}
        {isEditing ? (
          <input
            value={firstName}
            onChange={e => {
              setFirstName(e.target.value)
            }}
          />
        ) : (
          <b>{firstName}</b>
        )}
      </label>
      <label>
        Last name:{' '}
        {isEditing ? (
          <input
            value={lastName}
            onChange={e => {
              setLastName(e.target.value)
            }}
          />
        ) : (
          <b>{lastName}</b>
        )}
      </label>
      <button type="submit">
        {isEditing ? 'Save' : 'Edit'} Profile
      </button>
      <p><i>Hello, {firstName} {lastName}!</i></p>
    </form>
  );
}
label { display: block; margin-bottom: 20px; }

Compare this solution to the original imperative code. How are they different?

Refactor the imperative solution without React

Here is the original sandbox from the previous challenge, written imperatively without React:

```js src/index.js active function handleFormSubmit(e) { e.preventDefault(); if (editButton.textContent === 'Edit Profile') { editButton.textContent = 'Save Profile'; hide(firstNameText); hide(lastNameText); show(firstNameInput); show(lastNameInput); } else { editButton.textContent = 'Edit Profile'; hide(firstNameInput); hide(lastNameInput); show(firstNameText); show(lastNameText); } }

function handleFirstNameChange() { firstNameText.textContent = firstNameInput.value; helloText.textContent = ( 'Hello ' + firstNameInput.value + ' ' + lastNameInput.value + '!' ); }

function handleLastNameChange() { lastNameText.textContent = lastNameInput.value; helloText.textContent = ( 'Hello ' + firstNameInput.value + ' ' + lastNameInput.value + '!' ); }

function hide(el) { el.style.display = 'none'; }

function show(el) { el.style.display = ''; }

let form = document.getElementById('form'); let editButton = document.getElementById('editButton'); let firstNameInput = document.getElementById('firstNameInput'); let firstNameText = document.getElementById('firstNameText'); let lastNameInput = document.getElementById('lastNameInput'); let lastNameText = document.getElementById('lastNameText'); let helloText = document.getElementById('helloText'); form.onsubmit = handleFormSubmit; firstNameInput.oninput = handleFirstNameChange; lastNameInput.oninput = handleLastNameChange;


```js sandbox.config.json hidden
{
  "hardReloadOnChange": true
}

```html public/index.html

Hello, Jane Jacobs!


Imagine React didn't exist. Can you refactor this code in a way that makes the logic less fragile and more similar to the React version? What would it look like if the state was explicit, like in React?

If you're struggling to think where to start, the stub below already has most of the structure in place. If you start here, fill in the missing logic in the `updateDOM` function. (Refer to the original code where needed.)

```js src/index.js active
let firstName = 'Jane';
let lastName = 'Jacobs';
let isEditing = false;

function handleFormSubmit(e) {
  e.preventDefault();
  setIsEditing(!isEditing);
}

function handleFirstNameChange(e) {
  setFirstName(e.target.value);
}

function handleLastNameChange(e) {
  setLastName(e.target.value);
}

function setFirstName(value) {
  firstName = value;
  updateDOM();
}

function setLastName(value) {
  lastName = value;
  updateDOM();
}

function setIsEditing(value) {
  isEditing = value;
  updateDOM();
}

function updateDOM() {
  if (isEditing) {
    editButton.textContent = 'Save Profile';
    // TODO: show inputs, hide content
  } else {
    editButton.textContent = 'Edit Profile';
    // TODO: hide inputs, show content
  }
  // TODO: update text labels
}

function hide(el) {
  el.style.display = 'none';
}

function show(el) {
  el.style.display = '';
}

let form = document.getElementById('form');
let editButton = document.getElementById('editButton');
let firstNameInput = document.getElementById('firstNameInput');
let firstNameText = document.getElementById('firstNameText');
let lastNameInput = document.getElementById('lastNameInput');
let lastNameText = document.getElementById('lastNameText');
let helloText = document.getElementById('helloText');
form.onsubmit = handleFormSubmit;
firstNameInput.oninput = handleFirstNameChange;
lastNameInput.oninput = handleLastNameChange;

```js sandbox.config.json hidden { "hardReloadOnChange": true }


```html public/index.html
<form id="form">
  <label>
    First name:
    <b id="firstNameText">Jane</b>
    <input
      id="firstNameInput"
      value="Jane"
      style="display: none">
  </label>
  <label>
    Last name:
    <b id="lastNameText">Jacobs</b>
    <input
      id="lastNameInput"
      value="Jacobs"
      style="display: none">
  </label>
  <button type="submit" id="editButton">Edit Profile</button>
  <p><i id="helloText">Hello, Jane Jacobs!</i></p>
</form>

<style>
* { box-sizing: border-box; }
body { font-family: sans-serif; margin: 20px; padding: 0; }
label { display: block; margin-bottom: 20px; }
</style>

The missing logic included toggling the display of inputs and content, and updating the labels:

```js src/index.js active let firstName = 'Jane'; let lastName = 'Jacobs'; let isEditing = false;

function handleFormSubmit(e) { e.preventDefault(); setIsEditing(!isEditing); }

function handleFirstNameChange(e) { setFirstName(e.target.value); }

function handleLastNameChange(e) { setLastName(e.target.value); }

function setFirstName(value) { firstName = value; updateDOM(); }

function setLastName(value) { lastName = value; updateDOM(); }

function setIsEditing(value) { isEditing = value; updateDOM(); }

function updateDOM() { if (isEditing) { editButton.textContent = 'Save Profile'; hide(firstNameText); hide(lastNameText); show(firstNameInput); show(lastNameInput); } else { editButton.textContent = 'Edit Profile'; hide(firstNameInput); hide(lastNameInput); show(firstNameText); show(lastNameText); } firstNameText.textContent = firstName; lastNameText.textContent = lastName; helloText.textContent = ( 'Hello ' + firstName + ' ' + lastName + '!' ); }

function hide(el) { el.style.display = 'none'; }

function show(el) { el.style.display = ''; }

let form = document.getElementById('form'); let editButton = document.getElementById('editButton'); let firstNameInput = document.getElementById('firstNameInput'); let firstNameText = document.getElementById('firstNameText'); let lastNameInput = document.getElementById('lastNameInput'); let lastNameText = document.getElementById('lastNameText'); let helloText = document.getElementById('helloText'); form.onsubmit = handleFormSubmit; firstNameInput.oninput = handleFirstNameChange; lastNameInput.oninput = handleLastNameChange;


```js sandbox.config.json hidden
{
  "hardReloadOnChange": true
}

```html public/index.html

Hello, Jane Jacobs!

```

The updateDOM function you wrote shows what React does under the hood when you set the state. (However, React also avoids touching the DOM for properties that have not changed since the last time they were set.)


Sitemap

Overview of all docs pages