REACT Forms

Sneha Mallik
Last Updated: May 13, 2022

Introduction 

Forms are an essential component of React web apps. From a login screen to a checkout page, users can enter and upload information directly into the components. Because the majority of applications in React are SPAs(single-page applications) or web applications that dynamically load one page with updated information, you won't be sending data to a server straight from the form. Instead, you'll use an extra JavaScript file to capture and submit or display the information in the form on the client-side.

Why React Forms?

Handling React Forms is an important part of many online web applications, and it's one of React's strong suits. You have a lot of flexibility in implementing and controlling those input controls, and there are many other approaches to accomplish the same purpose.

React forms are unique as in that you can manage this React form feature by setting and altering its input value directly, or you can use React to let the browser process and gather data through React Change Events. Because they can be reused, react formats are unique. React does not set the value, this is the first option known as an uncontrolled component. As React actively changes the inputs, the second method is a controlled component.

 

In this blog, we are going to build react forms that will handle form submissions, with which we will look upon an example demo of building forms. We will also come to know about a variety of forms using checkboxes, text inputs, select lists, etc.

Building React forms

HTML form components differ from other DOM(Document Object Model) components because the form components have an internal status.

 

React form has the default HTML form browsing behavior of opening a new page whenever the user submits the form. If you want this behavior in React forms, it will just work. However, in most cases, a JavaScript function that handles form submission and accesses the form's user data is recommended. The traditional method is to use a technique known as 'controlled components’.

 

Form components like <select>, <input>, and <textarea> in HTML often keep their own state and change it based on user input.

The <select> Tag

Select tag in HTML allows us to utilize a dropdown menu to select from a variety of options. Adjusting selected options based on a specific dropdown is what we’ll look upon. It is quite straightforward to achieve with React with the help of the State. It is a brief for people who are unconcerned about the state.

render(){
    return(
        <form>
            <label> Choose a destination: </label>
            <select value = {this.state.location} 
            onChange={this.handleLocationChange}>
                <option></option>
                <option value="Paris"></option>
                <option value="New York"></option>
                <option value="London"></option>
                <option value="Switzerland"></option>
            </select>
        </form>
    );
}

NOTE: 

  • You can utilize third-party tools like react-select to reduce the amount of boilerplate code.

npm i --save react-select

OR

yarn add react-select

 

  • The selected attribute can be used to select an option initially.

The <input> Tag

The File API(Application Programming Interface) in JavaScript allows the user to upload or alter one or more files from the device's storage via HTML.

<input type = "text" />
NOTE: The <input> tag in React is an uncontrolled component as its value can be set by the user and cannot be done programmatically.

The <textarea> Tag

The text of a <textarea> element in HTML is defined by its children:

<form>
    <textarea>
        This is a demo for the textarea element.
    </textarea>
</form>

In React, a <textarea> uses a value attribute instead.

export default class Application extends Component{
    state = {intro: ''};
    handleIntroChange = (e) =>{
        const bio = e.target.value;
        this.setState({intro});
    };
    render(){
        return(
            <form>
                <label>Introduction: </label>
                <textarea value = {this.state.intro} 
                onChange={this.handleIntroChange}>
                </textarea>
            </form>
        );
    }
}
NOTE: Textarea is used to gather multi-line feedback from the user. It's not like a regular text entry box, which only accepts one-line input. A Textarea example is an address field in a form.

The state of these input elements in React is usually saved in the component's state property and only updated with setState().

Controlled Components

A controlled component is assigned a value, and its changes are handled in code via event-based callbacks. The input form variable is dealt with by React rather than the DOM in this case. The mutable state is kept in the state property and updated with setState() in this scenario.

 

The functions of controlled components regulate the data that occurs at each onChange event. This information is then recorded and updated in the setState() method. It makes it easy for components to manage the form's elements and data.

 

The controlled component is a state-based method of handling form input. If you're using React Hooks, you may alter the form input value in a single step, and when the user starts typing setState or useState characters, this state can be called and updated using a single event, such as onChange.

 

We can use the controlled component when making the following:

  • Forms validation, so that you must always know the input value to check if it is valid or not when typing!
  • If you have a format, such as the input for the credit card.
  • Unless there is valid data in all fields, disable the submit icon.

Conditional Rendering Method

Single-page applications(SPAs) that are dynamic and highly interactive can be created. One function that makes this possible is conditional rendering.

 

If a condition is true or false, conditional rendering defines how various user interface markups can be rendered. As a result, we can make different aspects or components depending on the condition. This concept is applied in the following scenarios:

 

  • Rendering data from an external API
  • Elements can be displayed or hidden
  • The toggling application's functionality
  • Implementation at the permit level
  • Management of authentication and approval

 

Prerequisites for building React Forms

  • Development environment running Node.js.
  • Create a React app in the React development environment.
  • React events and hooks will be used, including the useState() and useReducer() hooks.
  • Basic knowledge of HTML and JavaScript.

 

Creating a React Form with useState Hook

As it comes to handling forms, it's all about how we manage the data when it changes or gets submitted.

 

In HTML, form data is normally handled via the Document Object Model (DOM).

 

Form data is often handled by the components in React.

 

All data is kept in the component state when it is handled by the components. We add event handlers to the onChange attribute to govern changes.

 

The useState Hook can be used to keep track of the values of each input.

 

const { useState } = React

const Application = () => {
  
  const [input, setValue] = useState("");
  const [name, setName] = useState('Welcome to CodingNinjas');
  
  handleInput = (event) => {
    setValue(event.target.value);
  }
  
  updateName = (event) => {
    event.preventDefault();
    setName(input);
    setValue("");
  }
  
  return (
    <div className="box">
      <h1>
        Hello, <span>{name}!</span>   
      </h1>
      
      <form className="form">
        
        <div class="field">
          <label for="name-1">Update Name</label>
          <div class="control">
            <input type="text" value={input} name="name-1" onChange={handleInput} class="input"/>
          </div>
        </div>
        <div class="field">
          <div class="control">
            <button onClick={updateName} class="button is-dark">Save</button>
          </div>
        </div>
      </form>
      
    </div>
  )
}

ReactDOM.render(<Application />, document.getElementById("root"));

 

OUTPUT:

 

Upon running it on the local server, we get the following output.

We will now update the name to ‘Learn something new today!’.

On clicking the ‘Save’ button, the output will be,

 

 

Frequently Asked Questions

 

  1. How do you create forms in React?

Forms in React are similar to those in HTML. However, with React, the state is stored in the component's state property and can only be modified using setState(). As a result, the elements can't update their state directly, thus a JavaScript function handles their submission. This function has complete access to the information that a user enters into a form.

 

2. What are the uncontrolled and controlled components? 

Uncontrolled Components

Controlled Components

These maintain their own state.These do not maintain their own state.
DOM controls the data.Here, the parent component controls the data.
To acquire their current values, refs are used.They use props to get current values and then use callbacks to alert them of changes.

Key Takeaways

In this blog, we went over the fundamentals of React forms. Online web applications rely on react forms. You can link and manipulate forms and elements in React using a variety of methods. You may dynamically update properties, including value input elements, just like other components. Uncontrolled components are ideal for simplicity, but they may not be appropriate in cases when data must be erased or pre-populated. Controlled components provide you more ways to update the data, but they can also introduce an extra layer of abstraction, which might lead to accidental issues or re-renders.

 

React allows you the flexibility to dynamically update and adapt your forms to the needs of your application and your users, regardless of your methodology.

 

Enroll in our Advance Front-end Web Development Course- React.js to deeply understand the concept of react forms in Web Development. And developers, if you are preparing for the following interview, check out the blogs 15 Most Frequently Asked React JS Interview Questions and 10 Best ReactJS Interview Questions

 

Credits: GIPHY

 

Happy Developing!

Was this article helpful ?
0 upvotes

Comments

No comments yet

Be the first to share what you think