React keywords: useState

Project overview:

Project shows: Each functional component has its own file. Reacts ‘useState(…)’ hook is used to define and manipulate props for both the App and its child components. The parent App() accesses child state props through event handlers that it passes to its child components, when the child components calls the event handler they can pass their state props into the function. This is known as lifting state up.

The parent App() exposes itself to the DOM (index.js) through ‘export default function App() {…}’. Child component files expose themselves to the parent using the same ‘export default function Child()’ convention. The App() uses the ‘handle…’ naming convention for all event handlers it passes to its child components.

– The child components file ‘Form.js’ contains ‘export default function Form({ onAddItems }) {…’ which uses:

   <form className=“add-form” onSubmit={handleSubmit}> where:

    The Form’s ‘function handleSubmit(e) {…’ calls back to the parents ‘onAddItems(newItem); …}’ which adds the new item to the parent’s items[] array. This is known as lifting state up from the form(…) component to the App() component.

   Similar ‘handle…()’ event handlers are passed from the parent to child components like:

   ‘<input … onChange={() => onToggleItem(item.id)} …}’
   ‘<button onClick={() => onDeleteItem(item.id)}>’
   ‘<Item … onDeleteItem={onDeleteItem} onToggleItem={onToggleItem} … />’
   ‘<button onClick={onClearList}>’

Code:

<!DOCTYPE html>
<html lang=“en”>
  <head>
    <meta charset=“utf-8” />
    <link rel=“icon” href=“%PUBLIC_URL%/favicon.ico” />
    <meta name=“viewport” content=“width=device-width, initial-scale=1” />
    <meta name=“theme-color” content=“#000000” />
    <meta
      name=“description”
      content=“Web site created using create-react-app”
    />
    <link rel=“apple-touch-icon” href=“%PUBLIC_URL%/logo192.png” />
    <!–
      manifest.json provides metadata used when your web app is installed on a
      user’s mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
    –>
    <link rel=“manifest” href=“%PUBLIC_URL%/manifest.json” />
    <!–
      Notice the use of %PUBLIC_URL% in the tags above.
      It will be replaced with the URL of the `public` folder during the build.
      Only files inside the `public` folder can be referenced from the HTML.

      Unlike “/favicon.ico” or “favicon.ico”, “%PUBLIC_URL%/favicon.ico” will
      work correctly both with client-side routing and a non-root public URL.
      Learn how to configure a non-root public URL by running `npm run build`.
    –>
    <title>React App</title>
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id=“root”></div>
    <!–
      This HTML file is a template.
      If you open it directly in the browser, you will see an empty page.

      You can add webfonts, meta tags, or analytics to this file.
      The build step will place the bundled scripts into the <body> tag.

      To begin the development, run `npm start` or `yarn start`.
      To create a production bundle, use `npm run build` or `yarn build`.
    –>
  </body>
</html>
import React from “react”;
import ReactDOM from “react-dom/client”;
import “./index.css”;
import App from “./Components/App”;

const root = ReactDOM.createRoot(document.getElementById(“root”));
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);
/*const initialItems = [
  { id: 1, description: “Passports”, quantity: 2, packed: false },
  { id: 2, description: “Socks”, quantity: 12, packed: true },
  { id: 3, description: “Charger”, quantity: 1, packed: false },
];*/

export default function App() {
  //const [items, setItems] = useState(initialItems);
  const [items, setItems] = useState([]);

  function handleAddItems(item) {
    setItems((items) => [items, item]);
  }

  function handleDeleteItem(id) {
    setItems((items) => items.filter((item) => item.id !== id));
  }

  function handleToggleItem(id) {
    setItems((items) =>
      items.map((item) =>
        item.id === id ? { item, packed: !item.packed } : item
      )
    );
  }

  function handleClearList() {
    const confirmed = window.confirm(
      “Are you sure you want to delete all items?”
    );

    if (confirmed) setItems([]);
  }

  return (
    <div className=“app”>
      <Logo />
      <Form onAddItems={handleAddItems} />
      <PackingList
        items={items}
        onDeleteItem={handleDeleteItem}
        onToggleItem={handleToggleItem}
        onClearList={handleClearList}
      />
      <Stats items={items} />
    </div>
  );
}
import { useState } from “react”;

export default function Form({ onAddItems }) {
  const [description, setDescription] = useState(“”);
  const [quantity, setQuantity] = useState(1);

  function handleSubmit(e) {
    e.preventDefault();

    if (!description) return;

    const newItem = { description, quantity, packed: false, id: Date.now() };
    console.log(newItem);

    onAddItems(newItem);

    setDescription(“”);
    setQuantity(1);
  }

  return (
    <form className=“add-form” onSubmit={handleSubmit}>
      <h3>What do you need for your 😍 trip?</h3>
      <select
        value={quantity}
        onChange={(e) => setQuantity(Number(e.target.value))}
      >
        {/*<option value={1}>1</option>
          <option value={2}>2</option>
          <option value={3}>3</option>*/}
        {Array.from({ length: 20 }, (_, i) => i + 1).map((num) => (
          <option value={num} key={num}>
            {num}
          </option>
        ))}
      </select>
      <input
        type=“text”
        placeholder=“Item…”
        value={description}
        onChange={(e) => {
          setDescription(e.target.value);
        }}
      />
      <button>Add</button>
    </form>
  );
}
export default function Item({ item, onDeleteItem, onToggleItem }) {
  return (
    <li>
      <input
        type=“checkbox”
        value={item.packed}
        onChange={() => onToggleItem(item.id)}
      />
      <span style={item.packed ? { textDecoration: “line-through” } : {}}>
        {item.quantity} {item.description}
      </span>
      <button onClick={() => onDeleteItem(item.id)}>❌</button>
    </li>
  );
}
export default function Logo() {
  return <h1>w🌴 Far Away 💼</h1>;
}
export default function Stats({ items }) {
  if (!items.length)
    return (
      <p className=“stats”>
        <em>Start adding some items to your packing list ✈️</em>
      </p>
    );

  const numItems = items.length;
  const numPacked = items.filter((item) => item.packed).length;
  const percentage = Math.round((numPacked / numItems) * 100);

  return (
    <footer className=“stats”>
      <em>
        {percentage === 100
          ? “You got everything! Ready to go ✈️”
          : ` 💼 You have ${numItems} items on your list, and you already packed ${numPacked} (${percentage}%)`}
      </em>
    </footer>
  );
}
/*
const initialItems = [
  { id: 1, description: “Passports”, quantity: 2, packed: false },
  { id: 2, description: “Socks”, quantity: 12, packed: false },
];
*/

@import url(“https://fonts.googleapis.com/css2?family=Monoton&family=Quicksand:wght@500;700&display=swap”);

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

html {
  font-size: 62.5%;
}

body {
  font-size: 2.4rem;
  font-family: sans-serif;
  color: #5a3e2b;
  font-family: “Quicksand”;
  font-weight: 500;
}

.app {
  width: 100%;
  height: 100vh;
  display: grid;
  grid-template-rows: auto auto 1fr auto;
}

h1 {
  text-align: center;
  background-color: #f4a226;
  font-family: “Monoton”;
  font-size: 8rem;
  text-transform: uppercase;
  font-weight: 400;
  word-spacing: 30px;
  letter-spacing: -5px;
  padding: 2.4rem 0;
}

.add-form {
  background-color: #e5771f;
  padding: 2.8rem 0;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0.8rem;
}

h3 {
  margin-right: 1.6rem;
  font-size: 2.4rem;
}

button,
select,
input {
  background-color: #ffebb3;
  color: #5a3e2b;
  font-family: inherit;
  border: none;
  border-radius: 10rem;
  padding: 1.2rem 3.2rem;
  font-weight: 700;
  font-size: 1.8rem;
  cursor: pointer;
}

.add-form button {
  text-transform: uppercase;
  background-color: #76c7ad;
}

.list {
  background-color: #5a3e2b;
  color: #ffebb3;
  padding: 4rem 0;

  display: flex;
  justify-content: space-between;
  flex-direction: column;
  gap: 3.2rem;
  align-items: center;
}

.actions button,
.list select {
  text-transform: uppercase;
  padding: 0.8rem 2.4rem;
  font-size: 1.4rem;
  font-weight: 700;
  margin: 0 0.8rem;
}

.list ul {
  list-style: none;
  width: 80%;
  overflow: scroll;

  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 1.2rem;
  justify-content: center;
  align-content: start;
}

.list li {
  display: flex;
  align-items: center;
  gap: 1.2rem;
}

input[type=“checkbox”] {
  height: 2rem;
  width: 2rem;
  accent-color: #e5771f;
}

.list li button {
  cursor: pointer;
  background: none;
  border: none;
  font-size: 1.8rem;
  padding: 0.8rem;
  transform: translateY(2px);
}

.stats {
  background-color: #76c7ad;
  text-align: center;
  font-weight: 700;
  padding: 3.2rem 0;
}