react js-tutorial

React Forms

Each and every modern web application needs forms. It enables user interaction with the application and data collection from users. Depending on the nature of your business requirements and logic, forms can carry out a wide range of operations, including user authentication, user addition, searching, filtering, booking, and ordering. Text fields, buttons, checkboxes, radio buttons, and more can all be found on a form.

Making a Form

React provides a stateful, reactive method for creating forms. The React form is often handled by the component rather than the DOM. React typically uses controlled components to implement forms.

In React, form input often comes in one of two flavours.

  • uncontrollable element
  • regulated element

How to Create Forms with Plain React

Let’s dive right in. We’re going to build a simple contact form. Here’s the first iteration, a standalone component called ContactForm that renders a form:

function ContactForm() {
  return (
    <form>
      <div>
        <label htmlFor="name">Name</label>
        <input id="name" type="text" />
      </div>
      <div>
        <label htmlFor="email">Email</label>
        <input id="email" type="email" />
      </div>
      <div>
        <label htmlFor="message">Message</label>
        <textarea id="message" />
      </div>
      <button type="submit">Submit</button>
    </form>
  );
}

None of this requires you to install a library. Because forms are supported by HTML and the DOM, React comes with built-in form support. React’s primary function is rendering DOM nodes.

In fact, you most likely don’t even need a form library for simple forms. If you just need a basic form, something like Formik or react-hook-form is overkill.

Although there isn’t a state set up yet, and we aren’t responding to form submissions, this component will already display an interactive form. (If you submit it, the page will reload as the browser is still handling submission in the default manner.)

Two Kinds of Inputs: Controlled vs. Uncontrolled

Uncontrolled Input

It resembles a basic HTML input the most. React places it there, and the browser manages the rest. React offers a mechanism to obtain the input’s value when you need to. Although less code is needed, uncontrolled inputs make some tasks more challenging.

Example

In this example, the code accepts a field username and company name in an uncontrolled component.

import React, { Component } from 'react';  
class App extends React.Component {  
  constructor(props) {  
      super(props);  
      this.updateSubmit = this.updateSubmit.bind(this);  
      this.input = React.createRef();  
  }  
  updateSubmit(event) {  
      alert('You have entered the UserName and CompanyName successfully.');  
      event.preventDefault();  
  }  
  render() {  
    return (  
      <form onSubmit={this.updateSubmit}>  
        <h1>Uncontrolled Form Example</h1>  
        <label>Name:  
            <input type="text" ref={this.input} />  
        </label>  
        <label>  
            CompanyName:  
            <input type="text" ref={this.input} />  
        </label>  
        <input type="submit" value="Submit" />  
      </form>  
    );  
  }  
}  
export default App;  

Output

When you execute the above code, you will see the following screen.

After filling the data in the field, you get the message that can be seen in the below screen.

Controlled Input

You have explicit control over the value that it displays. To respond to key presses, you must create code that stores the current value somewhere and passes it back to the input so that it may be shown. The centre of the feedback loop is your code. Wiring these up requires more human labour, however they provide

Example

import React, { Component } from 'react';  
class App 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('You have submitted the input successfully: ' + this.state.value);  
      event.preventDefault();  
  }  
  render() {  
      return (  
          <form onSubmit={this.handleSubmit}>  
            <h1>Controlled Form Example</h1>  
            <label>  
                Name:  
                <input type="text" value={this.state.value} onChange={this.handleChange} />  
            </label>  
            <input type="submit" value="Submit" />  
         </form>  
      );  
  }  
}  
export default App;  

Output

When you execute the above code, you will see the following screen.

After filling the data in the field, you get the message that can be seen in the below screen.

RECOMMENDED ARTICLES





Leave a Reply

Your email address will not be published.