Generic input handler with React JS

Snir Lugassy
2 min readApr 21, 2017

--

Mainly when people start to learn React, they are confused from the new mindset of controlling values and the data flow.

In React, we will handle input and output with 2 different approaches: Controlled and uncontrolled.

Uncontrolled — We let the inputs act freely with user input, and when we need to use the data (Submit button click for example) we will refer to the inputs and ask for the data.

Controlled — The name is telling us everything, We are controlling the data using the Component’s state and handle functions to manage the data.

The generic input handler is more relevant to the Controlled components, where we have function that handle the state.

React sometimes feels a little redundant, especially in small stuff like inputs But actually, it makes your code well-organized, very understandable and scaleable.

When I started to learn React I tried making a survey form, that contains few text inputs.
I accomplish that by adding event handler onChage={this....} to every input in the form, which use this.setState({...}) and change the state according to the input.

But was I supposed to add handler function to each input in the form?
And if I have 10 inputs, it would be 10 functions, and it seems ridicules.

So I used the following solution:
By adding to every input ‘name’ or ‘id’ that are equal to the key in the state, I could use these properties and refer to the right value in the state.

Let’s write a “CoolForm” Component, With controlled inputs, that implements this generic handler:

import React from 'react'export default class CoolForm extends React.Component {  
constructor(props) {
super(props);
this.handleInputChange = this.handleInputChange.bind(this);
this.state = {
formData: {
firstName: '',
lastName: '',
email: '',
isCool: false
}
}
}

handleInputChange(e) {
let formData = Object.assign({}, this.state.formData);
formData[e.target.name] = e.target.value;
this.setState({formData})
}

render() {
return (
<form action="/survey/new" method="post">
<input
type="text"
name="firstName"
onChange={this.handleInputChange)} />
<input
type="text"
name="lastName"
onChange={this.handleInputChange)} />
<input
type="text"
name="email"
onChange={this.handleInputChange)} />
<select
name="isCool"
onChange={this.handleInputChange)}>
<option value={false}>No</option>
<option value={true}>Yes</option>
</select>
</form>
)
}
}

e.target.name Helps us to point to the right key-value pair in the state.

--

--