Working with forms in React.js

In simple html form, the form elements keeps value with it internally and submit on form submission button.


<!DOCTYPE html>
<title>Form Example</title>
      User Name:
      <input type="text" name="username" />
   <input type="submit" value="Submit Form" />

In above example, we have a simple input called username and we can receive its value on form submission. The default behavior of html form is to navigate to new page i.e. the post form submission page.

But it can give more advantage if we have a form submission handler JavaScript function which can validate the form data as well. The validation will give the relevant feedback to user.

React has a technique to handle form submission which is called as controlled components.

As in html, the elements like input, textarea etc keeps their own state and updates based on user actions. In React the mutable fields are kept with state object.

Handling username field in React’s approach of controlled component −

class UserForm extends React.Component {
   constructor(props) {
      this.state = {username: ''};
      this.handleChange = this.handleChange.bind(this);
      this.handleSubmit = this.handleSubmit.bind(this);
   handleChange(event) {
   handleFormSubmit(event) {
      console.log('username: ' + this.state.username);
   render() {
      return (
         <form onSubmit={this.handleFormSubmit}>
               <input type="text" value={this.state.username} onChange={this.handleUsernameChange} />
            <input type="submit" value="Submit" />

Here we have onChange handler function for updating state field username.

On formSubmit we are just showing console log in browser to display the submitted user name.

The other controlled type of components are textarea, select tag , radio buttons etc.

There are some uncontrolled component as well like file type which are read only in nature and only gets their value on form submission.

Handling multiple form inputs with single JS function −

handleInputChange(event) {
   const value =;
   const name =;
      [name]: value

Controlled input with null value for fields should be avoided by providing a default value for fields using state initiations.

For full scale solutions on form handling in React can be done using third party libraries like formik. It’s simple to use validations, feedback to user and more.