Skip to content

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.

We’re practicing setting up the project from scratch (to reinforce earlier concepts).

  1. Open your workbook to src\D\nextjs-event-state-fundamentals-START and run the following in your terminal.

    src\D\nextjs-event-state-fundamentals-START
    npx create-next-app@latest state-events-intro

    Use “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
  2. Install additional MUI packages

    src\D\nextjs-event-state-fundamentals-START
    npm install @mui/material @emotion/react @emotion/styled
    npm install-scripts approve --all
  3. 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>
    <div
    className={`${styles.page} ${geistSans.variable} ${geistMono.variable}`}
    >
    <main className={styles.main}>
    </main>
    </div>
    </>
    );
    }
  4. 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>
    <link
    rel="stylesheet"
    href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap"
    />
    </Head>
    <body>
    <Main />
    <NextScript />
    </body>
    </Html>
    );
    }
  5. Run the project using npm run dev. You should see a blank page with the NextJS logo in the bottom left.

  6. 🚦 Do a git commit of your setup so far.

  1. 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>
  2. Create a new component at components/TodoList.js with 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
    // #endregion
    return <>
    <Grid item xs={12}>
    My To-Do App
    </Grid>
    </>
    }
  3. Import and use that component in your index.js so that you can see the results as we develop the component.

  4. Let’s begin by adding a <TextField> for user input.

    components/TodoList.js
    return <>
    <TextField
    id="standard-basic"
    label="New Todo?"
    variant="standard"
    sx={{width: '100%'}}
    />
    <Grid item xs={12}>
    My To-Do App
    </Grid>
    </>
    }
  5. 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 Handlers
    const onTodoTextChange = (event) => {
    console.log(event.target.value);
    }
    components/TodoList.js
    return <>
    <TextField
    id="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.

  6. 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 Management
    const [todoText, setTodoText] = useState("");
    // #endregion

    Note how we give our initial todoText value an empty string (the argument passed into useState()).

  7. Wire that into the <TextField> and the event handler.

    components/TodoList.js
    // #region Event Handlers
    const onTodoTextChange = (event) => {
    console.log(event.target.value);
    setTodoText(event.target.value);
    }
    // #endregion
    return <>
    <TextField
    id="standard-basic"
    label="New Todo?"
    variant="standard"
    sx={{width: '100%'}}
    onChange={onTodoTextChange}
    value={todoText}
    />
  8. 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 App
    Current input text: {todoText}
    </Grid>
    </>
    }
  9. 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 Management
    const [todoText, setTodoText] = useState("");
    const [allTodos, setAllTodos] = useState([]);
    // #endregion
  10. 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 Handlers
    const onTodoTextChange = (event) => {
    console.log(event.target.value);
    setTodoText(event.target.value);
    }
    const onAddTodoClick = () => {
    // Temporary, just to confirm you've wired it up
    console.log("clicked");
    // create a new list that has allTodos and the new todos.
    const newAllTodoList = [...allTodos, todoText];
    console.log(newAllTodoList);
    // set the todoList
    setAllTodos(newAllTodoList);
    // reset the value of the todo text.
    setTodoText("");
    }
    // #endregion
    components/TodoList.js
    <TextField
    id="standard-basic"
    label="New Todo?"
    variant="standard"
    sx={{width: '100%'}}
    onChange={onTodoTextChange}
    value={todoText}
    />
    <Button
    variant="contained"
    onClick={onAddTodoClick}
    >Add Todo</Button>
    <Grid item xs={12}>
    Current input text: {todoText}
  11. 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 below
    import { 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>
  12. 🚦 Do a git commit of your final project.