react get form values on submit 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: react forms

class NameForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {value: ''};
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleChange(event) {    this.setState({value: event.target.value});  }
  handleSubmit(event) {
    alert('A name was submitted: ' + this.state.value);
    event.preventDefault();
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <label>
          Name:
          <input type="text" value={this.state.value} onChange={this.handleChange} />        </label>
        <input type="submit" value="Submit" />
      </form>
    );
  }
}

Example 3: 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
   });
}