save form data in react js code example

Example 1: How to Submit Forms and Save Data with React.js

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>
      );
   }
}

Example 2: How to Submit Forms and Save Data with React.js

handleInputChange(event) {
   const value = event.target.value;
   const name = event.target.name;
   this.setState({
      [name]: value
   });
}