Start learning free

LESSON 77 OF 161 · FRONTEND: REACT COMPONENTS AND STATE

Show One Thing or Another

Practice

A component is a function, so it can decide what to draw with a plain if. When one case is special, check it at the top and return early: the function ends there, and the code below it never runs for that case.

Here is the idea on another component, a badge for a product's stock:

function Badge({ stock }) {
  if (stock === 0) {
    return <p>Sold out</p>;
  }
  return <p>{stock} left</p>;
}

A button can be switched off with the disabled attribute: it stays on the screen, but clicks do nothing. Today src/Cart.jsx draws an empty list and Total: $0 for an empty cart, and it has no Checkout button at all.

The check opens the page, clicks Checkout, adds a Mug and removes it again. Your page must show:

> open the page
      text: Your cart is empty
      button: Checkout (disabled)
> click "Checkout"
      (it is disabled: nothing happens)
> click "Add to cart" in "Mug"
  -   text: Your cart is empty
  -   button: Checkout (disabled)
  +   list
  +     item: Mug × 1 $12
  +       button: Remove Mug
  +   text: Total: $12
  +   button: Checkout
> click "Remove Mug"
      back to "Your cart is empty" and a disabled Checkout

Your task: in src/Cart.jsx, return early when lines is empty, with a paragraph Your cart is empty and a disabled Checkout button. Under the total of a full cart, add a Checkout button that works.


Assignment
Follow the Coding Tutorial to give the cart an early return for the empty case and a Checkout button for the full one.


Hint
An empty array has length 0. Two elements side by side in one return need a fragment, <>…</>.


STEP 1 OF 3
    Ctrl + Enter to check