React Forms

Handling forms is about how you handle the data when it changes value or gets submitted.

In HTML, form data is usually handled by the DOM.

In React, form data is usually handled by the components.

When the data is handled by the components, all the data is stored in the component state.

You can control changes by adding event handlers in the onChange attribute:

import React from 'react';

class Form extends React.Component {
   constructor(props) {
      super(props);
      
      this.state = {
         firstName: 'Folau'
      }
      this.updateState = this.updateState.bind(this);
   };

   updateState(e) {
      this.setState({firstName: e.target.value});
   }

   render() {
      return (
         <div>
            <input type = "text" value = {this.state.firstName} 
               onChange = {this.updateState} />
            <h4>{this.state.firstName}</h4>
         </div>
      );
   }
}
export default Form;

You must initialize the state in the constructor method before you can use it.

You get access to the field value by using the event.target.value syntax.

Submitting Form

You can control the submit action by adding an event handler in the onSubmit attribute.

import React from 'react';
import ReactDOM from 'react-dom';

class Form extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      username: '',
      age: null,
    };
  }
  mySubmitHandler = (event) => {
    event.preventDefault();
    alert("You are submitting " + this.state.username);
  }
  myChangeHandler = (event) => {
    let nam = event.target.name;
    let val = event.target.value;
    this.setState({[nam]: val});
  }
  render() {
    return (
      <form onSubmit={this.mySubmitHandler}>
      <h1>Hello {this.state.username} {this.state.age}</h1>
      <p>Enter your name:</p>
      <input
        type='text'
        name='username'
        onChange={this.myChangeHandler}
      />
      <p>Enter your age:</p>
      <input
        type='text'
        name='age'
        onChange={this.myChangeHandler}
      />
      <input
        type='submit'
      />
      </form>
    );
  }
}

ReactDOM.render(<Form />, document.getElementById('root'));

 

Note that we use event.preventDefault() to prevent the form from actually being submitted.

 It’s convenient to have a JavaScript function that handles the submission of the form and has access to the data that the user entered into the form. The standard way to achieve this is with a technique called “controlled components”.

 

 




Subscribe To Our Newsletter
You will receive our latest post and tutorial.
Thank you for subscribing!

required
required


Leave a Reply

Your email address will not be published. Required fields are marked *