Handling State of Multiple Form Input

Kingsley Silas Chijioke
tiltblog
Published in
1 min readJun 6, 2018

React makes the management of state in an input text easy, for controlled components. You can do this:

class App extends Component {
state = {
username: ''
}
handleInputChange = (event) => {
this.setState({ username: event.target.value
}
}

Then in your form, you set the value of the input to the state.

<form>
<input
type="text"
value={this.state.username}
placeholder="Username"
onChange={handleInputChange} />
</form>

Straightforward right?

Problem

What happens when you have multiple form inputs? Oops…

handleUsernameChange = (event) => {
this.setState({ username: event.target.value})
}
handlePasswordChange = (event) => {
this.setState({ password: event.target.value})
}
handleEmailChange = (event) => {
this.setState({ email: event.target.value})
}

And you can go on and on like that, more like a callback hell. I should call this handle input hell. I’ve been in this same situation many times, and I have had to search for a solution online.

Solution

The way around this is to make use of the input’s name. So for my form, I should have:

<form>
<input
type="text"
name="email"
value={this.state.email}
placeholder="Email"
onChange={this.handleInputChange}
/>
<input
type="text"
name="username"
value={this.state.username}
placeholder="Username"
onChange={this.handleInputChange}
/>
<input
type="text"
name="fullname"
value={this.state.fullname}
placeholder="Full Name"
onChange={this.handleInputChange}
/>
</form>

For the method,

handleInputChange = (event) => {
this.setState({ [event.target.name]: event.target.value })
}

--

--