Monday, May 18, 2020

ReactJS Forms

ReactJS Forms


Forms


The forms are basically used to take user input from the user interface. There are many form input elements such as input text, password, textarea, select, etc. These elements work little differently in React from other regular HTML tags because they maintain their state in their own way. However, a form follows default behavior to pass information to another page in React also. 

<html>   
<body> 
<h2> Form Demo</h2> 
<script>
function doSomething()
{
alert('Welcome '+document.getElementById('name').value);
}
</script> 
<form onsubmit='doSomething()'>
<input type='text' id='name' placeholder='Enter name'/><br/>
<input type='submit' value='submit'/>
</form> 
</body>  
</html>  

In React, we can maintain the state of the ReactJS component by ReactJS state object that is mutable. We can set the state by the setState() method. We can create a combination of these two behaviors by making the React component state a “single source of truth”. As a consequence, React that is responsible for rendering the component will also control the outcome of user input.

Controlled Components

A controlled component is an input form element whose value is controlled by React. The same HTML form can be created and controlled in ReactJS such as, 

class MyForm 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('Welcome ' + this.state.value);
    event.preventDefault();
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
          <input type="text" value={this.state.value} 
          onChange={this.handleChange} 
          placeholder='Enter your name'/><br/>
        <input type="submit" value="Submit" />
      </form>
    );
  }
}
ReactDOM.render(<MyForm/>,document.getElementById('root'));

<textarea> tag


The <textarea> tag is used to take large textual user input from the user.

A controlled form with <textarea> can be created as,

class FeedbackForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      value: 'Write your feedback here'
    };

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleChange(event) {
    this.setState({value: event.target.value});
  }

  handleSubmit(event) {
    alert('Your feedback is submitted: ' + this.state.value);
    event.preventDefault();
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
      <textarea value={this.state.value} 
      onChange={this.handleChange}/><hr/>        
      <input type="submit" value="Submit" />
      </form>
    );
  }
}
ReactDOM.render(<FeedbackForm/>,document.getElementById('root'));

<select> tag


The <select> tag is used to take input from a dropdown in HTML. A controlled form having a <select> tag can be created such as,

class ColorForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {value: 'RED'};

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleChange(event) {
    this.setState({value: event.target.value});
  }

  handleSubmit(event) {
    alert('You choosed ' + this.state.value);
    event.preventDefault();
  }

  render() {
    const colors=this.props.options;
    const coloropt=colors.map(function(clr){
      return <option value={clr}>{clr}</option>;
    });
    
    return (
      <form onSubmit={this.handleSubmit}>
          <select value={this.state.value} 
          onChange={this.handleChange}>
          {coloropt}
          </select>
        <input type="submit" value="Submit" />
      </form>
    );
  }
}

const opt=['RED','BLUE','ORANGE','YELLOW','GREEN'];
ReactDOM.render(<ColorForm options={opt}/>,
document.getElementById('root'));

<input type='file'> tag

This tag is a read-only tag, so it can not be controlled by React.

Handling multiple input fields





We can handle multiple input fields using multiple state attributes. We can associate the name attribute to the input fields to identify them individually.

class ComplexForm extends React.Component {
  constructor(props) {
     super(props);
     
     this.state = {
        dataName: '',
        dataPassword:''
     }
     this.updateStateName = this.updateStateName.bind(this);
     this.updateStatePass = this.updateStatePass.bind(this);
     this.handleSubmit = this.handleSubmit.bind(this);
  };
  updateStateName(event) {
     this.setState({dataName: event.target.value});   
  }
  updateStatePass(event) {
    this.setState({dataPassword: event.target.value});   
 }
 handleSubmit(event)
 {
   alert('User-> ' + this.state.dataName+' 
   with password'+this.state.dataPassword+' is trying to login');
  event.preventDefault();
 }
  render() {
     return (
        <div><form onSubmit={this.handleSubmit}>
           <input type = "text" 
              onChange = {this.updateStateName} 
              placeholder='Enter name'/><br/>
           <input type="password" 
              onChange = {this.updateStatePass}
              placeholder='Enter password'/><br/>
           <input type="submit" value="submit"/>
           </form>
        </div>
     );
  }
}
ReactDOM.render(<ComplexForm />,
document.getElementById('root'));