Using Event Handlers in React

Alex Waller
2 min readMay 16, 2021

When building React applications, it definitely makes sense to use Redux. Redux provides a store in which we can house the state of our application. This is our Redux State, which is basically a snapshot of our application at any given moment. Whether a dropdown menu is clicked or not, which page we are currently on, the array of data being shown can all be part of the Redux State. While Redux state is more global and long term, React State, or state that exists within components, is typically more for short term goals like setting values for input fields.

While using state for a form can seem tedious, it is actually very good practice. Using state for the form will make data retrieval much easier. Since all our React components and Redux store, actions, and reducers will all need to work in sync to make a successful application work, event handlers will be crucial to making this happen.

Let’s dive into some code. Here, were are working with a form. Within the context of the application, the user is an employee for a corporation that is tracking hybrids they have manufactured as they travel across the country. Therefore, the user enters information about an individual hybrid to be submitted to the database. Since a form’s initial state will most likely have empty input fields, the state will have every text field set to an empty string.

class HybridsForm extends Component {

state = {

name: ‘ ’,

species: ‘ ’,

origin: ‘ ’,

personality: ‘ ’,

image: ‘ ’

}

Great, but obviously the form isn’t of much use if we can’t type into the input fields. Since we’ll need to use the setState() method so we continuously change the state of the input fields to whatever the user wishes to type in. In order to do this, we will need to create a function to enable this state change.

handleChange = e => {

const { name, value } = e.target

this.setState({

[name]: value

})

}

Awesome! Writing this function brings us one step closer to being able type into a form that is controlled by local state. Now is where we will finally be able to use the much hyped Event Handlers.

onChange is an Event Handler we can use within our JSX to handle the state change. Since we have a big form here, I’m just going to write one row of it to make the example more concise:

<input type=‘text’ value={this.state.name}

onChange={this.handleChange} name= “name” />

As we can see here, the Event Handler onChange will invoke our function handleChange that handles our state change. Now, users will be able to type into the input fields, and we will be using good programming practices to build successful applications.

--

--