We're now using the useState
hook to initialize state for our app. This state consists of an array of task objects which we import from the tasks.js
file.
When the user clicks add task, we're now adding an onClick
hander on the button to add a new task. Inside the addTask
function, you'll see we are setting the tasks to a new array, constructed of the current tasks spread over the array (...tasks
) and a new task object.
The new task consists of a uniqueID (a random number we generate here) and a name set to "new task". You can have the tasks render the id to observe the number is random each time. We need a random ID here because we need to set the key
of the task to its own unique identifer per React's rules on rendering lists.
Your mission
Make the Task component a CSS Grid that has a right aligned section called "actions". This is where we will place our buttons. We have our own quick course on CSS Grid you can check out here to get familiar with grids.
import { useState } from "react"; import styled from "styled-components"; // Importing shared components import Header from "./Header"; import Subheader from "./Subheader"; import Button from "./Button"; import Task from "./Task"; import Card from "./Card"; import TasksContainer from "./TasksContainer"; // Importing data import tasksData from "./tasks"; function uniqueId() { return Math.floor(Math.random() * 10000000); } export default function App() { const [tasks, setTasks] = useState(tasksData); function addTask() { setTasks([...tasks, { id: uniqueId(), name: "New task" }]); } return ( <Card> <Header> 🏴☠️ Captain's Tasks </Header> <Subheader> Manage the daily jobs at sea </Subheader> <Button onClick={addTask}>+ Add Task</Button> <TasksContainer> {tasks.map(({ name, id }, i) => ( <Task key={`task-${id}`} name={name} id={id} /> ))} </TasksContainer> </Card> ); }