React

Level recap · React · Level 1

Components and props

Everything this level taught, class by class: the idea, the code and what it shows. Read it before the exam, or keep it as a PDF.

What this level teaches: Build pages from small parts that take data.

12 classesLevel exam

Take the level exam
  1. 1Your first component

    A component is a function that gives back JSX.

    The idea

    Ticket CL-101 from the web team lead: the new shop front starts today, and the first job is the top of the home page.

    In React, a page is built from components. A component is a JavaScript function whose name starts with a capital letter and that gives back what to draw. What it gives back is written in JSX, which looks like HTML inside JavaScript: return <h1>Copperleaf</h1>;.

    The code

    export default function App() {
      return (
        <main>
          <h1>Copperleaf</h1>
          <p>Desks, lamps and chairs for your home office.</p>
        </main>
      );
    }

    What it shows

    PASS The page has the heading Copperleaf
  2. 2Values in curly braces

    { } runs JavaScript inside JSX.

    The idea

    Ticket CL-102: the order page must show the order the customer just placed, not the same words for everyone.

    Inside JSX, curly braces { } hold JavaScript. <p>{order.id}</p> puts the value of order.id on the page, and {order.total.toFixed(2)} runs a method first. Text and braces mix freely: <p>Order {order.id}: {order.items} items</p>.

    The code

    const order = { id: "CL-2041", items: 3, total: 84.5 };
    export default function App() {
      return (
        <main>
          <h1>Your order</h1>
          <p>Order {order.id}: {order.items} items, ${order.total.toFixed(2)}</p>
        </main>
      );
    }

    What it shows

    PASS The page shows the order number and the item count from order
  3. 3A component of your own

    Write a part once and use it in many places.

    The idea

    Ticket CL-103: the shop's name appears at the top and at the bottom of every page. Design wants one piece of code for it, so a change is made once.

    Any function with a capital letter that gives back JSX is a component, and you use it like a tag: <Logo />. React calls the function and puts what it gives back on the page. Use it twice and it draws twice.

    The code

    function Logo() {
      return <span className="logo">Copperleaf</span>;
    }
    export default function App() {
      return (
        <div>
          <header><Logo /></header>
          <p>Free delivery on orders over $50.</p>
          <footer><Logo /></footer>
        </div>
      );
    }

    What it shows

    PASS Logo is a component that shows Copperleaf
  4. 4Props: data for a component

    A component gets its data as props.

    The idea

    Ticket CL-104: signed-in customers should see their own name at the top of the page.

    Props are the data a component gets, written like HTML attributes: <Greeting name="Sam" />. React hands them to the function as one object, and most teams unpack it right in the brackets: function Greeting({ name }) { ... }.

    The code

    function Greeting({ name }) {
      return <p>Welcome back, {name}.</p>;
    }
    export default function App() {
      return (
        <main>
          <h1>Copperleaf</h1>
          <Greeting name="Sam" />
        </main>
      );
    }

    What it shows

    PASS Greeting shows the name it gets
  5. 5Several props and a default

    Number props and a value for a missing prop.

    The idea

    Ticket CL-105: the product card needs the name, the price and how many are in stock. The warehouse feed sometimes leaves the stock out, and then the card must say 0.

    Props can be any value. Text goes in quotes, everything else in braces: <ProductCard name="Desk lamp" price={39.5} stock={12} />. To give a prop a value for when it is missing, write it in the brackets: function ProductCard({ name, price, stock = 0 }).

    The code

    function ProductCard({ name, price, stock = 0 }) {
      return (
        <article className="card">
          <h2>{name}</h2>
          <p>${price.toFixed(2)}</p>
          <p>{stock} in stock</p>
        </article>
      );
    }
    export default function App() {
      return (
        <div>
          <ProductCard name="Desk lamp" price={39.5} stock={12} />
          <ProductCard name="Notebook" price={4} />
        </div>
      );
    }

    What it shows

    PASS The card shows the name and the price with two decimals
  6. 6A list from an array

    map() turns an array into elements.

    The idea

    Ticket CL-106: the category page should list whatever products the catalog sends, ten or two hundred.

    Arrays become lists with map(): items.map((item) => <li key={item.id}>{item.name}</li>) gives back one <li> per product, and JSX draws an array of elements one after another. Put the map inside <ul> with braces.

    The code

    const products = [
      { id: 1, name: "Desk lamp" },
      { id: 2, name: "Notebook" },
      { id: 3, name: "Monitor arm" },
    ];
    function ProductList({ items }) {
      return (
        <ul>
          {items.map((item) => <li key={item.id}>{item.name}</li>)}
        </ul>
      );
    }
    export default function App() {
      return (
        <main>
          <h1>Desk accessories</h1>
          <ProductList items={products} />
        </main>
    …

    What it shows

    PASS ProductList shows one row per item, in order
  7. 7Keys that follow the item

    Why the key is the id, not the position.

    The idea

    Ticket CL-107, a bug report: a customer ticked the Desk lamp to compare it, pressed Sort by price, and the tick jumped to another product.

    React uses the key to tell which element is which between two draws. With key={index}, after sorting the first row is still "row 0", so React keeps its ticked box there, even though a different product now sits in it. With key={item.id}, the key moves with the product, and so does everything that belongs to it.

    The code

    const products = [
      { id: 7, name: "Desk lamp", price: 39.5 },
      { id: 3, name: "Notebook", price: 4 },
      { id: 9, name: "Monitor arm", price: 89 },
    ];
    export default function App() {
      const [sorted, setSorted] = React.useState(false);
      const rows = sorted ? [...products].sort((a, b) => a.price - b.price) : products;
      return (
        <main>
          <button onClick={() => setSorted(true)}>Sort by price</button>
          <ul>
            {rows.map((item, index) => (
              <li key={item.id}>
                <label><input type="checkbox" /> {item.name}, ${item.price.toFixed(2)}</label>
              </li>
            ))}
          </ul>
    …

    What it shows

    PASS Each row keeps its own key when the order changes
  8. 8Show it only when it applies

    if, and null for "draw nothing".

    The idea

    Ticket CL-108 from the warehouse: show "Out of stock" at 0, "Only 3 left" when fewer than 5 are left, and nothing at all when there are plenty.

    A component is a function, so it can use a normal if and give back different JSX. Giving back null means "draw nothing here": if (count >= 5) return null;. Write the tests from the top; the first one that is true gives back its JSX.

    The code

    function StockNote({ count }) {
      if (count === 0) return <p className="stock out">Out of stock</p>;
      if (count < 5) return <p className="stock low">Only {count} left</p>;
      return null;
    }
    export default function App() {
      return (
        <div>
          <h2>Desk lamp</h2><StockNote count={0} />
          <h2>Notebook</h2><StockNote count={3} />
          <h2>Backpack</h2><StockNote count={40} />
        </div>
      );
    }

    What it shows

    PASS At 0 it says Out of stock
  9. 9&& and ? : inside JSX

    Small choices inside the JSX, and the 0 trap.

    The idea

    Ticket CL-109, a bug report: products with no reviews show a stray "0" under the price. And a product with one review says "1 reviews".

    Inside JSX, cond && <p>...</p> draws the <p> only when cond is true. The trap: when cond is the number 0, 0 && ... gives back 0, and React draws a 0. Compare instead, so the test is a real true or false: count > 0 && ....

    The code

    function Reviews({ count }) {
      return (
        <div className="reviews">
          {count > 0 && <p>{count} {count === 1 ? "review" : "reviews"}</p>}
        </div>
      );
    }
    export default function App() {
      return (
        <div>
          <h2>Desk lamp</h2><Reviews count={14} />
          <h2>Phone stand</h2><Reviews count={1} />
          <h2>Wall clock</h2><Reviews count={0} />
        </div>
      );
    }

    What it shows

    PASS With 0 reviews nothing shows, not even a 0
  10. 10children: a box for any content

    The content between a component's tags.

    The idea

    Ticket CL-110 from design: every block on the account page sits in the same panel, a border and a title, but what is inside changes: an address, a list of orders, a form.

    What you write between a component's tags reaches it as the prop children: <Panel title="Address"><p>12 Mill Lane</p></Panel>. The component puts {children} where the content belongs. So one Panel frames anything.

    The code

    function Panel({ title, children }) {
      return (
        <section className="panel">
          <h2>{title}</h2>
          {children}
        </section>
      );
    }
    export default function App() {
      return (
        <div>
          <Panel title="Delivery address">
            <p>12 Mill Lane, Bristol</p>
          </Panel>
          <Panel title="Last order">
            <p>Order CL-2041: 3 items</p>
          </Panel>
        </div>
    …

    What it shows

    PASS The panel shows its title in an <h2>
  11. 11A page from parts

    Split a page into components that pass data down.

    The idea

    Ticket CL-111: the category page is one long function and hard to change. Split it: a header with the product count, the list, and a footer.

    Big pages are built from small components, each with one job. Data lives at the top, in App, and goes down as props: App knows the products, gives the count to Header and the array to ProductList. When the data changes, every part shows the new value, because each one reads it from its props.

    The code

    const products = [
      { id: 1, name: "Desk lamp" },
      { id: 2, name: "Notebook" },
      { id: 3, name: "Monitor arm" },
    ];
    function ProductList({ items }) {
      return <ul>{items.map((p) => <li key={p.id}>{p.name}</li>)}</ul>;
    }
    function Footer() {
      return <footer>Copperleaf, open every day</footer>;
    }
    function Header({ count }) {
      return (
        <header>
          <h1>Desk accessories</h1>
          <p>{count} products</p>
        </header>
      );
    …

    What it shows

    PASS Header shows the count it gets
  12. 12className and style

    Classes for the look, style for a value.

    The idea

    Ticket CL-112: the order tracker needs a progress bar that fills to the real percentage, and turns green when the order is delivered.

    In JSX, the HTML class attribute is written className, because class is a JavaScript word. It can be built with JavaScript: className={percent === 100 ? "bar done" : "bar"}.

    The code

    function Progress({ percent }) {
      return (
        <div className="track">
          <div className={percent === 100 ? "bar done" : "bar"} style={{ width: percent + "%" }}></div>
        </div>
      );
    }
    export default function App() {
      return (
        <div>
          <p>Order CL-2041: packed</p>
          <Progress percent={60} />
          <p>Order CL-1987: delivered</p>
          <Progress percent={100} />
        </div>
      );
    }

    What it shows

    PASS The bar is as wide as the percent

Ready for the exam? The level exam is one real task that uses what this recap covers.

Take the level exam