React Events and State - Part 1
When following along, make sure to do git commits (🚦) after each section!
State is what makes React so powerful, it’s a great way of keeping in sync what is displayed in your component and your JavaScript code.
Project Setup
Section titled “Project Setup”We’re practicing setting up the project from scratch (to reinforce earlier concepts).
-
Open your workbook to
src\D\nextjs-event-state-fundamentals-STARTand run the following in your terminal.src\D\nextjs-event-state-fundamentals-START npx create-next-app@latest state-events-introUse “customize settings” when prompted. Choose “No” for everything except the linting choice; use “ESLint”. This is the project structure we’re going to work with.
Directorycomponents We will create this folder ourselves
- TodoList.js The component we will create
Directorypages
Directoryapi/
- …
- _app.js
- _document.js
- index.js
Directorypublic/
- …
Directorystyles/
- …
- .gitignore
- .eslint.config.mjs
- jsconfig.json
- next.config.mjs
- package-lock.json
- package.json
- README.md
-
Install additional MUI packages
src\D\nextjs-event-state-fundamentals-START npm install @mui/material @emotion/react @emotion/stylednpm install-scripts approve --all -
Clean out the existing content in
index.js. It should now look like this.pages/index.js import Head from "next/head";import Image from "next/image";import { Geist, Geist_Mono } from "next/font/google";import styles from "@/styles/Home.module.css";const geistSans = Geist({variable: "--font-geist-sans",subsets: ["latin"],});const geistMono = Geist_Mono({variable: "--font-geist-mono",subsets: ["latin"],});export default function Home() {return (<><Head><title>Create Next App</title><meta name="description" content="Generated by create next app" /><meta name="viewport" content="width=device-width, initial-scale=1" /><link rel="icon" href="/favicon.ico" /></Head><divclassName={`${styles.page} ${geistSans.variable} ${geistMono.variable}`}><main className={styles.main}></main></div></>);} -
Add the Roboto font in the
<Head>of_document.js.pages/_document.js import { Html, Head, Main, NextScript } from "next/document";export default function Document() {return (<Html lang="en"><Head><linkrel="stylesheet"href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap"/></Head><body><Main /><NextScript /></body></Html>);} -
Run the project using
npm run dev. You should see a blank page with the NextJS logo in the bottom left. -
🚦 Do a
gitcommit of your setup so far.
ToDo List Component
Section titled “ToDo List Component”-
Add a container (docs here).
pages/index.js import Head from "next/head";import Image from "next/image";import { Geist, Geist_Mono } from "next/font/google";import styles from "@/styles/Home.module.css";import CssBaseline from '@mui/material/CssBaseline';import Box from '@mui/material/Box';import Container from '@mui/material/Container';pages/index.js <main className={styles.main}><CssBaseline /><Container maxWidth="sm"><Box sx={{ bgcolor: '#cfe8fc', height: '100vh' }}></Box></Container></main> -
Create a new component at
components/TodoList.jswith some minimal content. I recommend adding a couple of placeholder regions for content we’ll add in later steps.components/TodoList.js import { Box, Button, TextField, Grid } from '@mui/material';export default function TodoList() {// #region State Management// #endregion// #region Event Handlers// #endregionreturn <><Grid item xs={12}>My To-Do App</Grid></>} -
Import and use that component in your
index.jsso that you can see the results as we develop the component. -
Let’s begin by adding a
<TextField>for user input.components/TodoList.js return <><TextFieldid="standard-basic"label="New Todo?"variant="standard"sx={{width: '100%'}}/><Grid item xs={12}>My To-Do App</Grid></>} -
Hook up an event handler so that you have a place to process the user input. (You should see results in the browser’s dev tools’ console as you type in the input control.)
components/TodoList.js // #region Event Handlersconst onTodoTextChange = (event) => {console.log(event.target.value);}components/TodoList.js return <><TextFieldid="standard-basic"label="New Todo?"variant="standard"sx={{width: '100%'}}onChange={onTodoTextChange}/><Grid item xs={12}>My To-Do App</Grid></>}You can try out the input control in the browser and watch what happens in your browser’s console window.
-
Add some state management via React’s
useState()hook. (A “hook” is simply a function that allows you to “participate” in React’s rendering lifecycle.)components/TodoList.js import {useState} from 'react';import { Box, Button, TextField, Grid } from '@mui/material';export default function TodoList() {// #region State Managementconst [todoText, setTodoText] = useState("");// #endregionNote how we give our initial
todoTextvalue an empty string (the argument passed intouseState()). -
Wire that into the
<TextField>and the event handler.components/TodoList.js // #region Event Handlersconst onTodoTextChange = (event) => {console.log(event.target.value);setTodoText(event.target.value);}// #endregionreturn <><TextFieldid="standard-basic"label="New Todo?"variant="standard"sx={{width: '100%'}}onChange={onTodoTextChange}value={todoText}/> -
Add some basic rendering of the data so you can see it in the browser.
components/TodoList.js <Grid item xs={12}>My To-Do AppCurrent input text: {todoText}</Grid></>} -
Add another
useState()to track the results of all the to-do items. Notice how we initialize the state with an empty array (a reasonable starting point for a list of information).components/TodoList.js export default function TodoList() {// #region State Managementconst [todoText, setTodoText] = useState("");const [allTodos, setAllTodos] = useState([]);// #endregion -
Add a button to add items into our list of to-do tasks. We’ll also put in an event handler for the button click event.
components/TodoList.js // #region Event Handlersconst onTodoTextChange = (event) => {console.log(event.target.value);setTodoText(event.target.value);}const onAddTodoClick = () => {// Temporary, just to confirm you've wired it upconsole.log("clicked");// create a new list that has allTodos and the new todos.const newAllTodoList = [...allTodos, todoText];console.log(newAllTodoList);// set the todoListsetAllTodos(newAllTodoList);// reset the value of the todo text.setTodoText("");}// #endregioncomponents/TodoList.js <TextFieldid="standard-basic"label="New Todo?"variant="standard"sx={{width: '100%'}}onChange={onTodoTextChange}value={todoText}/><Buttonvariant="contained"onClick={onAddTodoClick}>Add Todo</Button><Grid item xs={12}>Current input text: {todoText} -
Render the information in a
<List>.components/TodoList.js import {useState} from 'react';import { Box, Button, TextField, Grid } from '@mui/material';// You can (probably should) combine the lines above and belowimport { List, ListItem, ListItemText, Typography } from '@mui/material';components/TodoList.js <Grid item xs={12}>Current input text: {todoText}<List sx={{width: `100%`}}>{allTodos.map((todoItem, index)=> {return <ListItem key={index}><ListItemText><Typography variant="p" component="div">{todoItem}</Typography></ListItemText></ListItem>})}</List></Grid> -
🚦 Do a
gitcommit of your final project.
Answered: 0 / 0 (0%)