How to use handleChange() function in react component?

MD Abul Bashar
3 min readMay 6, 2021

An onChange event is triggered when values are entered in the input. This fires a function handleChange(), that is used to set a new state for the input.

1. Handling Single Input

First, we have to set up the input field as a controlled component so that we have a controlled component that senses changes and updates the state accordingly.

We will learn handleChange() function with the help of a project in which we’re going to use handleChange() function to display the entered input.

Creating React App:

Step 1: Create a React application using the following command:

Step 2: After creating your project folder i.e. handlechange demo, move to it using the following command:

Project Structure: It will look like the following.

structure

App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.

JavaScript

Step to Run Application: Run the application using the following command from the root directory of the project:

Output:

The following will be the output if the user enters an input which is set with the help of handleChange() function as shown below:

2. Handling Multiple Input

In the above project write down the following code in the App.js file for handling multiple inputs.

Javascript

Step to Run Application: Run the application using the following command from the root directory of the project:

Output:

The following will be the output if the user enters an input which is set with the help of handleChange() function as shown below:

Explanation: We have added name property in case of multiple inputs so that we can identify which input field fired the handleChange() function. We have used the spread operator because when the handleChange() function has been fired, we need the current value of firstName and lastName (because only then we can add(or assign) the entered input to the state variables(firstName and lastName)) which are stored in the state object, so we used spread operator to take an existing state object.

How this [name]: value statement works?

This statement assigns the value to that input field whose name (Property) matches the value.

--

--