Working with forms in React.js

React JSJavascriptFront End Technology

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

Example

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

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) {
      super(props);
      this.state = {username: ''};
      this.handleChange = this.handleChange.bind(this);
      this.handleSubmit = this.handleSubmit.bind(this);
   }
   handleChange(event) {
      this.setState({username: event.target.value});
   }
   handleFormSubmit(event) {
      console.log('username: ' + this.state.username);
      event.preventDefault();
   }
   render() {
      return (
         <form onSubmit={this.handleFormSubmit}>
            <label>
               Name:
               <input type="text" value={this.state.username} onChange={this.handleUsernameChange} />
            </label>
            <input type="submit" value="Submit" />
         </form>
      );
   }
}

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 = event.target.value;
   const name = event.target.name;
   this.setState({
      [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.

raja
Published on 28-Aug-2019 08:45:33
Advertisements