Skip to content

React Events and State - Part 2

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 with a pre-set starter kit. In this, we’ll be filtering the results of a set of movie names, using React state in the process.

  1. Open your workbook to src\D\nextjs-event-state-jsx-conditionals-START\state-events-conditionals-example and take note of what files you have in this project. Run the following in your terminal.

    \state-events-conditionals-example
    npm install
    npm install-scripts approve --all
    npm run dev
  2. Open the browser. You should see the following data and form for user input.

    Starting point app

User input consists of two pieces of information: Some text in the movie’s name and the year of the movie. This is data that is important to the functionality of our component, so we can manage that state using React’s useState() hook.

  1. Import the useState “hook” so that we can create stateful variables.

    import { useState } from 'react'
  2. Create the variables under the function definition of Home.

    const [search, setSearch] = useState("")
    const [year, setYear] = useState("")
  3. Add the following lines for the search text field:

    <TextField
    {
    //other props here
    }
    onChange={(e)=> {setSearch(e.target.value)}}
    value={search}
    />
  4. Do the same for the year.

    <TextField
    {
    //other props here
    }
    onChange={(e)=> {setYear(e.target.value)}}
    value={year}
    />
  5. 🚦 Do a git commit of your project at this point.

All of the user input is meant to be processed when the user clicks the “Filter” button. This submits the form. Before we can do any actual filtering, we need to respond to the submit event.

  1. On the form tag we’re going to listen and handle form submissions, and we’re going to prevent the default action the way we’ve learned in the first level of js.

  2. Create the event handler for the form submission. We’re also going to print out the stateful variables we’ve created.

    const handleSubmit = (event) => {
    event.preventDefault()
    console.log(`year: ${year}`)
    console.log(`search: ${search}`)
    }

    You can see here that although react uses SyntheticEvent we can still use the method event.preventDefault() to prevent the form from submitting. You can also see that the year and search variables are updated to what the TextField currently are.

  3. On the form element we’re going to register this handler to the onSubmit event like so.

    <form
    style={{width: '100%'}}
    onSubmit={handleSubmit}
    >

    Observe now that that if you press enter or click the “filter” button after writing some text that the variables are printed out in the console.

  4. 🚦 Do a git commit of your project at this point.

Here is where we get into the meaty part of our example. Filtering is a process where we choose to show only some of the movies in our small dataset. The small subset is a piece of information we will track using React’s state management system: useState().

There’s a certain logic in how we’re constructing our example at this stage. We’ll make several observations at each step.

  1. We’re going to set a filter on the list so we want to create a filtered.

    • create a stateful variable named movies

      const [movies, setMovies] = useState(MOVIE_LIST)

    Note: here that the original value is the MOVIE_LIST as that’s what’s passed as an argument to the function useState.

  2. Change the line in the JSX (contained within the List component) as follows so that we can change what the list can be.

    // from this
    MOVIE_LIST.map((movieData, index)=> { /* more jsx stuff */ }
    // to this
    movies.map((movieData, index)=> {/* more jsx stuff */ }

    this will now use the new stateful variable of movies that you’ve created in the first step.

  3. Create a function called filterMovies that will use all of the variables so that it can be filtered in the correct way.

    const filterMovies = () => {
    // make a copy of the movie list.
    let filteredMovieList = [...MOVIE_LIST]
    // check if the search is empty
    if (search.trim() !== ""){
    // loop through the movies and check if the name
    // includes the search value (both lower case)
    filteredMovieList = filteredMovieList.filter((movieData)=> {
    return movieData.name.toLowerCase().includes(search.trim().toLowerCase())
    })
    }
    // check if the year is empty
    if (year.trim() !== ""){
    // loop through the movies and check if the year is the same as the
    filteredMovieList = filteredMovieList.filter((movieData)=> {
    return movieData.year === parseInt(year.trim())
    })
    }
    setMovies(filteredMovieList)
    }
  4. Let’s take a look at what this is doing.

    • the let filteredMovieList = [...MOVIE_LIST] is making a copy of the static movie list.
    • we then check to see if search is not empty, and we only filter if there is a value.
    • we loop filteredMovieList so that the new list is a subset of only the matches to the search queries.
      • remember that filter returns a new array and takes a boolean value true if you want to keep the result in the array and false if you want to filter it out.
      • note that the we are chaining methods together and that might be confusing so let’s break that down.
        • movieData.name is a string
        • .toLowerCase() is a method on a string that returns a string.
        • .includes is a method on a string (or array) that returns true or false which is why we’re using this in a filter. The search.trim().toLowerCase() is what we’re checking against.
    • we then check to see if year is not empty.
      • we filter through filteredMovieList so that the new list is a subset that only matches the year that we enter. Let’s break down what is going on in the filter.
        • the === operator will return true or false
        • on the left side we have movieData.year which is a number (you can see this in the utils/movies.js)
        • on the right we have parseInt(year.trim()) since year is a string we need to convert it to a number
    • last we use setMovies(filteredMovieList) which sets the variable movies so that the list in our jsx is updated.
  5. Let’s take a look at some conditionals and JSX by doing some error handling.

    • If you search for “test” you’ll see that there are no results and the page just looks blank.
    • we’re going to use the inline && logical operator to inform the users that there are no results.
    • In the List component add the following code that will display to the user “No results please search again.”
      {movies.length === 0 &&
      <ListItem>
      <ListItemText>
      <Typography variant="p" component="div">
      No results please search again.
      </Typography>
      </ListItemText>
      </ListItem>
      }

    Let’s take a deeper look at this.

    • movies.length === 0 is our condition which will return true or false
    • the && is the magic here, if the condition (on the left) is true it will display the the jsx below it. If the condition is false it does not show the jsx below the movies.length === 0 &&.

    Note: Test this by searching for “test” in the search bar.

  6. Let’s change this slightly to list the number of results on the page (replace the last step with the following)

    {movies.length === 0 ?
    <ListItem>
    <ListItemText>
    <Typography variant="p" component="div">
    No results please search again.
    </Typography>
    </ListItemText>
    </ListItem>
    :
    <ListItem>
    <ListItemText>
    <Typography variant="p" component="div">
    {movies.length} movie results
    </Typography>
    </ListItemText>
    </ListItem>
    }

    Let’s take a deeper look at this.

    • movies.length === 0 is our condition which will return true or false
    • the ? and the : is the magic here
      • if the condition (on the left) is true it will display the the jsx that is BEFORE the :.
      • if the condition (on the left) is false it will display the jsx that is AFTER the :.
  7. Let’s do one more validation to expand on this idea, our “year” TextField is a text field, in later versions we could change the type to number but that’s okay for now because we will check if the stateful year variable is a number.

    • in the component add the function
    const isNumber = (value) => {
    return !isNaN(value)
    }

    Note, if you would need to use this in another component it’s propbably a good idea to make a file in the utils/ folder and export this function.

    • we’re going to validate the search and display a message to the user, first we’re going to have to create a stateful variable called “errorMessage” like so the following:
    // other variables defined with useState
    const [errorMessage, setErrorMessage] = useState("")
    • we’re going to create a function named validateSearch search which is going to set an error message if the year is not a function like so.
    const validateSearch = () => {
    console.log("validateSearch")
    console.log(isNumber(year))
    // if the year is empty
    if (year.trim().length === 0) {
    setErrorMessage("")
    return
    }
    // check if the year isn't valid.
    if (!isNumber(year) || year.trim().length !== 4) {
    setErrorMessage(`"${year}" is not a valid year`)
    return
    }
    // this will only execute if the year is a number
    setErrorMessage("")
    }

    Let’s take a look here: if year.trim().length === 0 is empty then its fine, if !isNumber(year) || year.trim().length !== 4 is true then we have an error (if it’s not a number or if th year number is ridiculous). We also return early here. the last thing we do here is that we setErrorMessage("") because if our function has reached this point, there are no errors.

    • call the validateSearch function in the handleSubmit so every time we submit this gets called.
    const handleSubmit = (event) => {
    event.preventDefault()
    validateSearch()
    filterMovies()
    }
    • display the error message on the page.
    // change this
    {/* Add the error message here*/}
    // to
    { errorMessage !== "" &&
    <Alert severity="error">{errorMessage}</Alert>
    }

    You can see here that again we’re using the jsx conditional of && so that the error message will only show if errorMessage !== "" is true.

  8. 🚦 Do a git commit of your project at this point.