Learning Goals
At the end of this Tutorial, you will be able to:
- Add various components for updating numbers, strings and objects to a ReactJS app.
Adding stateful components
In this Lesson you will add some more stateful components to the counter app you built in the previous State and Hooks Lesson.
A component to update a number
Follow the steps below.
- To your app from the previous Lesson, add a new component with the following code.
import { useState } from 'react'; function DoubleNumber() { const [number, setNumber] = useState(4); function handleDoubleNumber() { setNumber(number * 2); } return ( <> <span>{number}</span> <button onClick={handleDoubleNumber}</button> </> ); } export default DoubleNumber;
- Next, convert the function statement to an anonymous function.
- Then, convert the anonymous function to an arrow function, and place it inline in the button event handler.
A component to update text
Follow the steps below.
- To your app from the previous Lesson, add a new component with the following code.
function TextUpdater() { // Initialize state with a default value const [text, setText] = useState('Initial text'); function HandleUpdateText() { setText('Updated text'); } return ( <> <span>{text}</span;> <button onClick={HandleUpdateText};>Update Text</button;> </> ); } export default TextUpdater;
- Next, amend the component with an if ... else clause so that it can detect the current text value, and change it to the alternative.
- Finally, rewrite the conditonal statement in the ternary operator syntax.
A component to update an object
Follow the steps below.
- To your app from the previous Lesson, add a new component with the following code.
function myCar() { const [brand, setBrand] = useState("Ford"); const [model, setModel] = useState("Mustang"); const [year, setYear] = useState("1964"); const [color, setColor] = useState("red"); return ( <> <h2>My {brand}>/h2> <p>It is a {color} {model} from {year}.</p> </> ); } export default MyCar;
- Add a button with an inline arrow function to update the color property of the MyCar object to "blue".
<button onClick={() => setColor("blue")}>Update Colour</button>
- Rewrite the code with object.property dot syntax as follows.
function MyCar() { const [car, setCar] = useState({ brand: "Ford", model: "Mustang", year: "1964", color: "red" }); const UpdateColor = () => { setCar(previousState => { return { ...previousState, color: "blue" } }); } return ( <> <h2>My {car.brand} car</h2> <p>It is a {car.color} {car.model} from {car.year}.</p> <p><button onClick={UpdateColor}>Update Colour</button></p> <> ); }