Forms are very useful in any web application. Unlike with Angular and AngularJS, which give you form validation out of the box, you have to handle forms yourself in React. This brings about many complications, like how to get form values, how to manage form state, and how to validate a form on the fly and show validation messages.

There are different methods and libraries out there to help with this, but if you’re like me and hate to be dependent on too many libraries, welcome on board. We’re going to bootstrap our own form from the ground up.

There are two types of form input in React. We have the uncontrolled input and the controlled input. The uncontrolled input are like traditional HTML form inputs, in that they remember what you typed. We will use ref to get the form values.

submitFormHandler = event => {
	  event.preventDefault();

	  console.dir(this.refs.name.value); //will give us the name value
	}

	render() {
	  return (
	      <div>

	        <form onSubmit={this.submitFormHandler}>
	          <div>
	            <input type="text" name="name" ref="name" />
	          </div>
	        </form>

	      </div>
	  );
	}

We added ref="name" to the input tag so that we can access the value with this.refs.name.value when the form is submitted. The downside to this is that you have to pull the value from the field when you need it, and this can happen when the form is submitted.

The controlled input is when the React component that renders a form also controls what happens in that form on subsequent user input. This means that, as form value changes, the component that renders the form saves the value in its state.

	import React, { Component } from 'react';

	class FormComponent extends Component {
	  constructor () {
	    this.state = {
	      email: ''
	    }
	  }

	  changeHandler = event => {
	    this.setState({
	      email: event.target.value
	    });
	  }

	  render () {
	    return (
	      <form>
	          <input type="email" 
	                 name="email"   
	                 value={this.state.email} 
	                 onChange={this.changeHandler} 
	          />
	      </form>
	    );        
	  }
	}

	export default FormComponent;

Of course, another component can handle the form state. The goal is that each time the input changes, the method changeHandler is called and will store the input state. Hence the component always has the current value of the input without needing to ask for it. This means that the form component can respond to input changes immediately; for example:

  • in-place feedback, like validation
  • disabling the button unless all fields have valid data
  • enforcing a specific input format

#reactjs #software-development #react #programming #javascript

The Complete Guide to Forms in React
2.05 GEEK