React

Modern React From The Beginning EP6: Event Handling


Subscribe On YouTube

Episodes

Handling of user events is an essential part in nearly every React web application. In this episode of the Modern React From The Beginning series you’ll learn how to handle standard user events in your React application. Therefore we’re going to extend our sample application with a new input field which will be user to enter a search term. For this field you’ll learn how to handle the Change and the KeyPressed event by adding corresponding event handler functions in the component.

Adding A Search Input Field

The first step is to add a new label and input field to component App:

const App = () => {
  return (
    <div>
      <h1>List of Courses</h1>
      <hr />

      <label htmlFor="searchInput">Search: </label>
      <input id="searchInput" type="text"/>
      
      <CoursesList courses={courses} />
    </div>
  );
}

export default App;

Handling The Change Event Of An Input Field

Now we’re ready to add a change event handler to the searchInput field. This is done by adding the onChange attribute to the input element and assigning a handler function as you can see in the following code:

const App = () => {
  const handleSearchInputChange = event => {
    console.log(event);
  }

  return (
    <div>
      <h1>List of Courses</h1>
      <hr />

      <label htmlFor="searchInput">Search: </label>
      <input id="searchInput" type="text" onChange={handleSearchInputChange} />
      
      <CoursesList courses={courses} />
    </div>
  );
}

The handler function is named handleSearchInputChange and implemented directly within the App component function. Again we’re making use of the arrow function syntax to define that function. handleSerachInputChange gets one parameter: event. This object is containing all event related information.

Accessing The Input Field Value Within The Event Handler Function

The event object can e.g. be used to access the value of the input field and printing it our to the console:

const handleSearchInputChange = event => {
    console.log(event.target.value);
}

Opening up the browser console will provide you with the corresponding output everytime you’re changing the input value:

10.png

Adding An Event Handler For The KeyPress Event

Let’s move on and add another event handler to the input field. Let’s also capture the KeyPressed event which is invoked each time a key is pressed:

      <input  id="searchInput"
              type="text"
              onChange={handleSearchInputChange}
              onKeyPress={handleSeachInputKeyPress} />

Here’re assigning the handleSearchInputKeyPress handler function which is implemented inside the App component function as well:

  const handleSeachInputKeyPress = event => {
    if (event.key === 'Enter') {
      console.log('Enter key pressed! Search Value: ' + event.target.value);
    }
  }

Inside this event handler function we’re checking of the enter key is pressed. If this is the case a corresponding output to the console is made:

20.png

In the following listing you can see the complete code of App.js again:

import React from 'react';
import CoursesList from './CoursesList';

const courses = [
  {
    id: 1,
    title: "React - The Complete Guide (incl Hooks, React Router, Redux)",
    author: "Maximilian Schwarzmüller",
    hours_video: 40.5,
    number_of_lectures: 490,
    rating: 4.6,
    url: "https://codingthesmartway.com/courses/react-complete-guide/"
  },
  {
    id: 2,
    title: "Modern React with Redux",
    author: "Stephen Grider",
    hours_video: 47.5,
    number_of_lectures: 488,
    rating: 4.6,
    url: "https://codingthesmartway.com/courses/modern-react-with-redux/"
  },
  {
    id: 3,
    title: "The Complete React Developer Course (w/ Hooks and Redux)",
    author: "Andrew Mead",
    hours_video: 39,
    number_of_lectures: 200,
    rating: 4.7,
    url: "http://codingthesmartway.net/courses/complete-react-web-app-developer/"
  }
];

const App = () => {
  const handleSearchInputChange = event => {
    console.log(event.target.value);
  }

  const handleSeachInputKeyPress = event => {
    if (event.key === 'Enter') {
      console.log('Enter key pressed! Search Value: ' + event.target.value);
    }
  }

  return (
    <div>
      <h1>List of Courses</h1>
      <hr />

      <label htmlFor="searchInput">Search: </label>
      <input  id="searchInput"
              type="text"
              onChange={handleSearchInputChange}
              onKeyPress={handleSeachInputKeyPress} />
      
      <CoursesList courses={courses} />
    </div>
  );
}

export default App;

What’s Next

In the next episode of this tutorial series we’re going to learn about React state and how state management can help us to manage data across components in out React application.

Advertisement: Top 3 React Online Courses

If you want to dive deeper and become a React pro also consider taking one of the following great online courses.

React – The Complete Guide (incl Hooks, React Router, Redux)*
Dive in and learn React.js from scratch! Learn Reactjs, Hooks, Redux, React Routing, Animations, Next.js and way more!

Go To Course*

Modern React with Redux*
Master React v16.6.3 and Redux with React Router, Webpack, and Create-React-App. Includes Hooks!

Go To Course*

The Complete React Developer Course (w/ Hooks and Redux)*
Learn how to build and launch React web applications using React, Redux, Webpack, React-Router, and more!

Go To Course*

* Affiliate Link / Advertisement: This blog post contains affiliate links, which means that if you click on one of the product links and buy a product, we’ll receive a small commission. There are no additional costs for you. This helps support the channel and allows us to continue to make videos like this. Thank you for the support!


Using and writing about best practices and latest technologies in web design & development is my passion.