+
+
+ ```
+
+=== ":material-play: Run"
+
+ ```html
+ # TODO
+ ```
Manipulating the UI imperatively works well enough for isolated examples, but it gets exponentially more difficult to manage in more complex systems. Imagine updating a page full of different forms like this one. Adding a new UI element or a new interaction would require carefully checking all existing code to make sure you haven't introduced a bug (for example, forgetting to show or hide something).
@@ -141,7 +145,7 @@ You've seen how to implement a form imperatively above. To better understand how
1. **Identify** your component's different visual states
2. **Determine** what triggers those state changes
-3. **Represent** the state in memory using `useState`
+3. **Represent** the state in memory using `use_state`
4. **Remove** any non-essential state variables
5. **Connect** the event handlers to set the state
@@ -159,136 +163,71 @@ First, you need to visualize all the different "states" of the UI the user might
Just like a designer, you'll want to "mock up" or create "mocks" for the different states before you add logic. For example, here is a mock for just the visual part of the form. This mock is controlled by a prop called `status` with a default value of `'empty'`:
-```js
-export default function Form({ status = "empty" }) {
- if (status === "success") {
- return
That's right!
;
- }
- return (
- <>
-
City quiz
-
- In which city is there a billboard that turns air into drinkable
- water?
-
-
- >
- );
-}
-```
+=== "app.py"
+
+ ```python
+ {% include "../../examples/managing_state/basic_form_component.py" start="# start" %}
+ ```
+
+=== ":material-play: Run"
+
+ ```python
+ # TODO
+ ```
You could call that prop anything you like, the naming is not important. Try editing `status = 'empty'` to `status = 'success'` to see the success message appear. Mocking lets you quickly iterate on the UI before you wire up any logic. Here is a more fleshed out prototype of the same component, still "controlled" by the `status` prop:
-```js
-export default function Form({
- // Try 'submitting', 'error', 'success':
- status = "empty",
-}) {
- if (status === "success") {
- return
That's right!
;
- }
- return (
- <>
-
City quiz
-
- In which city is there a billboard that turns air into drinkable
- water?
-
-
- >
- );
-}
-```
+=== "app.py"
-```css
-.Error {
- color: red;
-}
-```
+ ```python
+ {% include "../../examples/managing_state/conditional_form_component.py" start="# start" %}
+ ```
-
+=== "styles.css"
-#### Displaying many visual states at once
+ ```css
+ {% include "../../examples/managing_state/conditional_form_component.css" %}
+ ```
-If a component has a lot of visual states, it can be convenient to show them all on one page:
+=== ":material-play: Run"
-```js
-import Form from "./Form.js";
+ ```python
+ # TODO
+ ```
-let statuses = ["empty", "typing", "submitting", "success", "error"];
+!!! info "Deep Dive"
-export default function App() {
- return (
- <>
- {statuses.map((status) => (
-
-
Form ({status}):
-
-
- ))}
- >
- );
-}
-```
+ **Displaying many visual states at once**
-```js
-export default function Form({ status }) {
- if (status === "success") {
- return
That's right!
;
- }
- return (
-
- );
-}
-```
+ ??? "Show Details"
-```css
-section {
- border-bottom: 1px solid #aaa;
- padding: 20px;
-}
-h4 {
- color: #222;
-}
-body {
- margin: 0;
-}
-.Error {
- color: red;
-}
-```
+ If a component has a lot of visual states, it can be convenient to show them all on one page:
+
+ === "app.py"
-Pages like this are often called "living styleguides" or "storybooks".
+ ```python
+ {% include "../../examples/managing_state/multiple_form_components.py" start="# start" %}
+ ```
-
+ === "form.py"
+
+ ```python
+ {% include "../../examples/managing_state/conditional_form_component.py" start="# start" %}
+ ```
+
+ === "styles.css"
+
+ ```css
+ {% include "../../examples/managing_state/multiple_form_components.css" %}
+ ```
+
+ === ":material-play: Run"
+
+ ```python
+ # TODO
+ ```
+
+ Pages like this are often called "living styleguides" or "storybooks".
### Step 2: Determine what triggers those state changes
@@ -297,23 +236,18 @@ You can trigger state updates in response to two kinds of inputs:
- **Human inputs,** like clicking a button, typing in a field, navigating a link.
- **Computer inputs,** like a network response arriving, a timeout completing, an image loading.
-
-
-
-
+
-In both cases, **you must set [state variables](/learn/state-a-components-memory#anatomy-of-usestate) to update the UI.** For the form you're developing, you will need to change state in response to a few different inputs:
+In both cases, **you must set [state variables](./state-a-components-memory.md#anatomy-of-usestate) to update the UI.** For the form you're developing, you will need to change state in response to a few different inputs:
- **Changing the text input** (human) should switch it from the _Empty_ state to the _Typing_ state or back, depending on whether the text box is empty or not.
- **Clicking the Submit button** (human) should switch it to the _Submitting_ state.
- **Successful network response** (computer) should switch it to the _Success_ state.
- **Failed network response** (computer) should switch it to the _Error_ state with the matching error message.
-
+!!! abstract "Note"
-Notice that human inputs often require [event handlers](/learn/responding-to-events)!
-
-
+ Notice that human inputs often require [event handlers](./responding-to-events.md)!
To help visualize this flow, try drawing each state on paper as a labeled circle, and each change between two states as an arrow. You can sketch out many flows this way and sort out bugs long before implementation.
@@ -321,25 +255,20 @@ To help visualize this flow, try drawing each state on paper as a labeled circle
### Step 3: Represent the state in memory with `useState`
-Next you'll need to represent the visual states of your component in memory with [`useState`.](/reference/react/useState) Simplicity is key: each piece of state is a "moving piece", and **you want as few "moving pieces" as possible.** More complexity leads to more bugs!
+Next you'll need to represent the visual states of your component in memory with [`use_state`.](../reference/use-state.md) Simplicity is key: each piece of state is a "moving piece", and **you want as few "moving pieces" as possible.** More complexity leads to more bugs!
Start with the state that _absolutely must_ be there. For example, you'll need to store the `answer` for the input, and the `error` (if it exists) to store the last error:
-```js
-const [answer, setAnswer] = useState("");
-const [error, setError] = useState(null);
+```python linenums="0"
+{% include "../../examples/managing_state/necessary_states.py" start="# start" %}
```
Then, you'll need a state variable representing which one of the visual states that you want to display. There's usually more than a single way to represent that in memory, so you'll need to experiment with it.
If you struggle to think of the best way immediately, start by adding enough state that you're _definitely_ sure that all the possible visual states are covered:
-```js
-const [isEmpty, setIsEmpty] = useState(true);
-const [isTyping, setIsTyping] = useState(false);
-const [isSubmitting, setIsSubmitting] = useState(false);
-const [isSuccess, setIsSuccess] = useState(false);
-const [isError, setIsError] = useState(false);
+```python linenums="0"
+{% include "../../examples/managing_state/all_possible_states.py" start="# start" %}
```
Your first idea likely won't be the best, but that's ok--refactoring state is a part of the process!
@@ -350,826 +279,662 @@ You want to avoid duplication in the state content so you're only tracking what
Here are some questions you can ask about your state variables:
-- **Does this state cause a paradox?** For example, `isTyping` and `isSubmitting` can't both be `true`. A paradox usually means that the state is not constrained enough. There are four possible combinations of two booleans, but only three correspond to valid states. To remove the "impossible" state, you can combine these into a `status` that must be one of three values: `'typing'`, `'submitting'`, or `'success'`.
-- **Is the same information available in another state variable already?** Another paradox: `isEmpty` and `isTyping` can't be `true` at the same time. By making them separate state variables, you risk them going out of sync and causing bugs. Fortunately, you can remove `isEmpty` and instead check `answer.length === 0`.
-- **Can you get the same information from the inverse of another state variable?** `isError` is not needed because you can check `error !== null` instead.
+- **Does this state cause a paradox?** For example, `is_typing` and `is_submitting` can't both be `True`. A paradox usually means that the state is not constrained enough. There are four possible combinations of two booleans, but only three correspond to valid states. To remove the "impossible" state, you can combine these into a `status` that must be one of three values: `'typing'`, `'submitting'`, or `'success'`.
+- **Is the same information available in another state variable already?** Another paradox: `is_empty` and `is_typing` can't be `true` at the same time. By making them separate state variables, you risk them going out of sync and causing bugs. Fortunately, you can remove `is_empty` and instead check `len(answer) == 0`.
+- **Can you get the same information from the inverse of another state variable?** `is_error` is not needed because you can check `error != None` instead.
After this clean-up, you're left with 3 (down from 7!) _essential_ state variables:
-```js
-const [answer, setAnswer] = useState("");
-const [error, setError] = useState(null);
-const [status, setStatus] = useState("typing"); // 'typing', 'submitting', or 'success'
+```python linenums="0"
+{% include "../../examples/managing_state/refactored_states.py" start="# start" %}
```
You know they are essential, because you can't remove any of them without breaking the functionality.
-
-
-#### Eliminating “impossible” states with a reducer
+!!! info "Deep Dive"
-These three variables are a good enough representation of this form's state. However, there are still some intermediate states that don't fully make sense. For example, a non-null `error` doesn't make sense when `status` is `'success'`. To model the state more precisely, you can [extract it into a reducer.](/learn/extracting-state-logic-into-a-reducer) Reducers let you unify multiple state variables into a single object and consolidate all the related logic!
+ **Eliminating “impossible” states with a reducer**
-
+ These three variables are a good enough representation of this form's state. However, there are still some intermediate states that don't fully make sense. For example, a non-null `error` doesn't make sense when `status` is `'success'`. To model the state more precisely, you can [extract it into a reducer.](./extracting-state-logic-into-a-reducer.md) Reducers let you unify multiple state variables into a single object and consolidate all the related logic!
### Step 5: Connect the event handlers to set state
Lastly, create event handlers that update the state. Below is the final form, with all event handlers wired up:
-```js
-import { useState } from "react";
-
-export default function Form() {
- const [answer, setAnswer] = useState("");
- const [error, setError] = useState(null);
- const [status, setStatus] = useState("typing");
-
- if (status === "success") {
- return
- In which city is there a billboard that turns air into drinkable
- water?
-
-
- >
- );
-}
-
-function submitForm(answer) {
- // Pretend it's hitting the network.
- return new Promise((resolve, reject) => {
- setTimeout(() => {
- let shouldError = answer.toLowerCase() !== "lima";
- if (shouldError) {
- reject(new Error("Good guess but a wrong answer. Try again!"));
- } else {
- resolve();
- }
- }, 1500);
- });
-}
-```
+=== "app.py"
-```css
-.Error {
- color: red;
-}
-```
+ ```python
+ {% include "../../examples/managing_state/stateful_form_component.py" start="# start" %}
+ ```
+
+=== "styles.css"
+
+ ```css
+ {% include "../../examples/managing_state/conditional_form_component.css" %}
+ ```
+
+=== ":material-play: Run"
+
+ ```python
+ # TODO
+ ```
Although this code is longer than the original imperative example, it is much less fragile. Expressing all interactions as state changes lets you later introduce new visual states without breaking existing ones. It also lets you change what should be displayed in each state without changing the logic of the interaction itself.
-
+### Recap
- Declarative programming means describing the UI for each visual state rather than micromanaging the UI (imperative).
- When developing a component:
1. Identify all its visual states.
2. Determine the human and computer triggers for state changes.
- 3. Model the state with `useState`.
+ 3. Model the state with `use_state`.
4. Remove non-essential state to avoid bugs and paradoxes.
5. Connect the event handlers to set state.
-
+### Challenges
-
+=== "1. Add and remove a CSS class"
-#### Add and remove a CSS class
+
-Make it so that clicking on the picture _removes_ the `background--active` CSS class from the outer `
`, but _adds_ the `picture--active` class to the ``. Clicking the background again should restore the original CSS classes.
+ **Challenge 1 of 3: Add and remove a CSS class**
-Visually, you should expect that clicking on the picture removes the purple background and highlights the picture border. Clicking outside the picture highlights the background, but removes the picture border highlight.
+ Make it so that clicking on the picture _removes_ the `background--active` CSS class from the outer `
`, but _adds_ the `picture--active` class to the ``. Clicking the background again should restore the original CSS classes.
-```js
-export default function Picture() {
- return (
-
-
-
- );
-}
-```
+ Visually, you should expect that clicking on the picture removes the purple background and highlights the picture border. Clicking outside the picture highlights the background, but removes the picture border highlight.
-```css
-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;
-}
-
-.picture--active {
- border: 5px solid #a6b5ff;
-}
-```
+ === "picture.py"
-
-
-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](/learn/responding-to-events#stopping-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:
-
-```js
-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 (
-
` → first ``) has to line up. Otherwise, toggling `isActive` would recreate the whole tree below and [reset its state.](/learn/preserving-and-resetting-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
-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;
-```
+ This component has two visual states: when the image is active, and when the image is inactive:
-```js
-{
- "hardReloadOnChange": true
-}
-```
+ - 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`.
-```html
-
-
-
-```
+ 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](./responding-to-events.md#stopping-propagation) so that clicking the image doesn't register as a click on the background.
-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 (
-
- );
-}
-```
+ Verify that this version works by clicking the image and then outside of it:
-```css
-label {
- display: block;
- margin-bottom: 20px;
-}
-```
+ === "app.py"
-
-
-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](/learn/conditional-rendering) to show or hide the inputs depending on `isEditing`.
-
-```js
-import { useState } from "react";
-
-export default function EditProfile() {
- const [isEditing, setIsEditing] = useState(false);
- const [firstName, setFirstName] = useState("Jane");
- const [lastName, setLastName] = useState("Jacobs");
-
- return (
-
- );
-}
-```
+ ```python
+ {% include "../../examples/managing_state/stateful_picture_component.py" start="# start" %}
+ ```
-```css
-label {
- display: block;
- margin-bottom: 20px;
-}
-```
+ === "styles.css"
-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
-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;
-```
+ ```css
+ {% include "../../examples/managing_state/picture_component.css" %}
+ ```
-```js
-{
- "hardReloadOnChange": true
-}
-```
+ === ":material-play: Run"
-```html
-
-
-
-```
+ ```python
+ # TODO
+ ```
-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
-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;
-```
+ Alternatively, you could return two separate chunks of HTML:
-```js
-{
- "hardReloadOnChange": true
-}
-```
+ === "app.py"
-```html
-
-
-
-```
+ ```python
+ {% include "../../examples/managing_state/stateful_picture_component.py" start="# start" %}
+ ```
-
-
-The missing logic included toggling the display of inputs and content, and updating the labels:
-
-```js
-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;
-```
+ === "styles.css"
-```js
-{
- "hardReloadOnChange": true
-}
-```
+ ```css
+ {% include "../../examples/managing_state/picture_component.css" %}
+ ```
-```html
-
-
-
-```
+ === ":material-play: Run"
+
+ ```python
+ # TODO
+ ```
+
+ Keep in mind that if two different HTML chunks describe the same tree, their nesting (first `html.div` → first `html.img`) has to line up. Otherwise, toggling `is_active` would recreate the whole tree below and [reset its state.](./preserving-and-resetting-state.md) This is why, if a similar HTML tree gets returned in both cases, it is better to write them as a single piece of HTML.
+
+
+
+=== "2. Profile editor"
+
+
+
+ **Challenge 2 of 3: Profile editor**
-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.)
+ Here is a small form implemented with plain JavaScript and DOM. Play with it to understand its behavior:
-
+ === "index.js"
-
+ ```js
+ 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;
+ ```
+
+ === "index.html"
+
+ ```html
+
+
+
+ ```
+
+ 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!
+
+ === "app.py"
+
+ ```js
+ export default function EditProfile() {
+ return (
+
+ );
+ }
+ ```
+
+ === "styles.css"
+
+ ```css
+ label {
+ display: block;
+ margin-bottom: 20px;
+ }
+ ```
+
+ ??? note "Show Solution"
+
+ 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](./conditional-rendering.md) to show or hide the inputs depending on `isEditing`.
+
+ === "app.py"
+
+ ```js
+ import { useState } from "react";
+
+ export default function EditProfile() {
+ const [isEditing, setIsEditing] = useState(false);
+ const [firstName, setFirstName] = useState("Jane");
+ const [lastName, setLastName] = useState("Jacobs");
+
+ return (
+
+ );
+ }
+ ```
+
+ === "styles.css"
+
+ ```css
+ label {
+ display: block;
+ margin-bottom: 20px;
+ }
+ ```
+
+ === ":material-play: Run"
+
+ ```html
+ # TODO
+ ```
+
+ Compare this solution to the original imperative code. How are they different?
+
+
+
+=== "3. Refactor the imperative solution without React"
+
+
+
+ **Challenge 3 of 3: Refactor the imperative solution without React**
+
+ Here is the original sandbox from the previous challenge, written imperatively without React:
+
+ === "app.py"
+
+ ```js
+ 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;
+ ```
+
+ === "index.html"
+
+ ```html
+
+
+
+ ```
+
+ 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.)
+
+ === "app.py"
+
+ ```js
+ 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;
+ ```
+
+ === "index.html"
+
+ ```html
+
+
+
+ ```
+
+ ??? "Show solution"
+
+ The missing logic included toggling the display of inputs and content, and updating the labels:
+
+ === "app.py"
+
+ ```js
+ 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;
+ ```
+
+ === "index.html"
+
+ ```html
+
+
+
+ ```
+
+ === ":material-play: Run"
+
+ ```html
+ # TODO
+ ```
+
+ 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.)
+
+
Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.