Handling forms in React.js

React JSJavascript LibraryFront End Technology

Unlike other libraries like angular , forms in react need to handle by ourselves. There are two types of forms input in react

  • Controlled inputs
  • Uncontrolled inputs

Controlled components or elements are those which are handled by react functions. Example is updating the field on onChange function call. Most of the components are handled in controlled way.

Example for controlled form component

import React, { Component } from 'react';
class ControlledFormExample extends Component {
   constructor () {
      this.state = {
         email: ''
      }
   }
   changeEmailHandler = event => {
      this.setState({
         email: event.target.value
      });
   }
   render () {
      return (
         <form>
            <input type="email"
               name="email"
               value={this.state.email}
               onChange={this.changeEmailHandler}
            />
         </form>
      );
   }
}

export default ControlledFormExample

Here we are updating state whenever email input field changes.

If we have multiple fields in form, we can handle onChange for all in a single function like below −

handleChange(evt) {
   this.setState({ [evt.target.name]: evt.target.value });
}

In the above common state update, we should have name of field and state variable have same name.

Uncontrolled components are generally handled by DOM. We use ref to keep a reference to the element and handle it on submit action.

Example to demonstrate the uncontrolled handling of elements.

submitDataHandler = event => {
   event.preventDefault();
   console.log(this.refs.nameRef.value); //will give us the name value
}
render() {
   return (
      <div>
         <form onSubmit={this.submitDataHandler}>
            <div>
               <input type="text" name="name" ref="nameRef" />
            </div>
         </form>
      </div>
   );
}

We have to extract the field values in uncontrolled component to manipulate or handle submission.

We can add custom validations and display feedback to user.

import React, { Component} from 'react';
class FormExample extends Component {
   constructor(props) {
      super(props);
      this.state = {
         username: '',
         id: null,
         errormessage: ''
      };
   }
   myChangeHandler = (event) => {
      let nam = event.target.name;
      let val = event.target.value;
      let err = '';
      if (nam === "id") {
         if (val !="" && !Number(val)) {
            err = <strong>Your id must be a number</strong>;
         }
      }
      this.setState({errormessage: err});
      this.setState({[nam]: val});
   }
   render() {
      return (
         <form>
            <h1>Hello {this.state.username} {this.state.id}</h1>
            <p>Enter your name:</p>
            <input
               type='text'
               name='username'
               onChange={this.myChangeHandler}
            />
            <p>Enter your id:</p>
            <input
               type='text'
               name='id'
               onChange={this.myChangeHandler}
            />
            {this.state.errormessage}
         </form>
      );
   }
}
ReactDOM.render(<FormExample />, document.getElementById('root'));

The value of textarea is fetched with value attribute on it.

<textarea value={this.state.myText} />
class FormExample extends React.Component {
   constructor(props) {
      super(props);
      this.state = {
         myText: 'The content of textarea'
      };
   }
   render() {
      return (
         <form>
            <textarea value={this.state.myText} />
         </form>
      );
   }
}
ReactDOM.render(<FormExample />, document.getElementById('root'));
raja
Published on 04-Sep-2019 09:14:34
Advertisements