Start learning free

LESSON 75 OF 161 · FRONTEND: REACT COMPONENTS AND STATE

Arrays in State in JavaScript

Practice

A number was enough to count clicks. A real cart must remember which products were added, so its state becomes an array: one object per line, like { id: 1, name: "Mug", price: 12, quantity: 1 }.

React draws a component again only when its set function gets a new value. It compares the new value with the old one, and the very same array counts as no change. So push, which changes the old array in place, doesn't work: the check clicks and nothing changes. Make a new array instead, with the spread ..., which copies every item of the old one:

const [tags, setTags] = useState(["red"]);

function addTag(tag) {
  setTags([...tags, tag]);   // a new array: ["red", "blue"]
}

// in the markup: <p>{tags.length} tags</p>

The count is the array's length, computed on every draw, so it never needs a state of its own. The given src/Cart.jsx takes the array as its lines prop: it shows Your cart is empty, or one item per line with the name, the quantity and the price times the quantity.

The check opens the page and clicks two buttons:

> open the page                  →  text: Cart (0)  …  text: Your cart is empty
> click "Add to cart" in "Mug"   →  + text: Cart (1)   + item: Mug × 1 $12
> click "Add to cart" in "Lamp"  →  + text: Cart (2)   + item: Lamp × 1 $29

Your task: in src/App.jsx, keep the cart as an array in state, show Cart (…) from its length, make addToCart add a new line with a new array, and show the lines with a Cart inside a new Cart section.


Assignment
Follow the Coding Tutorial to turn the cart into an array in App's state, add lines to it the React way, and show them in a Cart section.


Hint
Never cart.push(line): give setCart a new array, the old lines spread out first and the new line last.


STEP 1 OF 6
    Ctrl + Enter to check

    React State Arrays in JavaScript

    Keep going with JavaScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free