React js form examples for beginners

Are you a beginner in react js and want to work with react js forms? In this react js tutorial, let us discuss everything about react js forms.

A form in a web application plays an important role as it helps to collect input from the site visitor and then send it to the backend for processing. Generally, when we create a form using HTML tags, the HTML handles form data using DOM. But, in the case of React, the form data is managed using components.

So, this ReactJs tutorial will illustrate how to create a form using react js components. Moreover, we will also discuss the following set of topics.

  • What are Forms in react js
  • Different ways to create Forms in React js
  • form in react js functional component
  • form in react js hooks
  • How to build dynamic forms in react js

Forms in react js

Forms are an essential component of every modern web application. It enables users to engage with the application as well as collect information from them.

Forms can execute a variety of functions depending on the nature of your business requirements and logic, such as user authentication, user addition, searching, filtering, booking, ordering, and so on. A form may include text fields, buttons, checkboxes, radio buttons, and so on.

Read Form validation in react js

Form in React js Example

Here we will see a simple example of how to render the Form component in react js.

Example: React submit the form on button click

In this example, we want to use a form to collect some input data from a user. For example, we want the user to select a Full name and click Submit.

Let’s say the index.html contains the below code:

  <div id="root"></div>

The Index.js file is the starting point of the React app, so it contains the below code:

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
    <App />
  
);
reportWebVitals();

The App.js file contains the below code:

import './App.css';
import Form from './Form';
import React, {Component} from "react";
class App extends Component {
	render() {
  	return (
    	<div className='App'>
        <Form />
    	</div>
    );
  }	
}

export default App;

In the Form component write the below code:

import React, {Component} from "react";
class Form extends Component {
	render() {
  	return (
    	<form>
    	  <input 
          type="text" 
          placeholder="Enter Full Name" 
          required 
        />
        <button>Submit</button>
    	</form>
    );
  }
}
export default Form;

Now run the application with the npm start command, and you can see the Form render on the page.

Form in React js Example
Form in React js Example

Read What is JSX in React js

Various ways to create Forms in React js

React provides a stateful, reactive method for building forms. The React form is usually handled by the component rather than the DOM. The form in React is typically constructed using controlled components.

In React, there are two sorts of form input:

Uncontrolled component
Controlled component

The uncontrolled component in React

Uncontrolled input is identical to standard HTML form inputs. The form data is handled by the DOM. The HTML elements here keep their own state, which is updated as the input value changes.

To retrieve form values from the DOM when writing an uncontrolled component, you must use a ref. To put it another way, there is no need to write an event handler for every state change. You can use a ref to get the form’s input field value from the DOM.

In this example, an uncontrolled component accepts a field username and department name.

Let’s say the index.html contains the below code

  <div id="root"></div>

The Index.js file is the starting point of the React app, so it contains the below code:

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
    <App />
  
);
reportWebVitals();

The App.js file contains the below code:


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

Now run the application with the npm start command, and you can see the form render on the page. Then fill out the form and click on Submit, then the success message pop up on the page.

uncontrolled form in react
uncontrolled form in react js

The controlled component in React

Form elements in HTML often keep their own state and update it based on user input. In the controlled component, the input form element is handled by the component rather than the DOM. The mutable state is stored in the state property and can only be updated with the setState() method

Instead of capturing data only once, as when you click a submit button, controlled components include methods that manage the data going into them on every onChange event. This information is then saved to the state and updated using the setState() method. This gives the component more control over the form elements and data.

A controlled component takes its current value via Props and announces changes as Callbacks onChange events. A parent component “handles” these changes by handling the callback and managing its own state, and then propagating the new values ​​as props to the controlled component. Also called a “dumb component”.

In this example, a controlled component accepts a field Fullname.

Let’s say the index.html contains the below code

  <div id="root"></div>

The Index.js file is the starting point of the React app, so it contains the below code:

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
    <App />
  
);
reportWebVitals();

The App.js file contains the below code:

import './App.css';

import React, { Component } from 'react';  
class App extends Component {  
  constructor(props) {  
      super(props);  
      this.state = {result: ''};  
      this.handleOnChange = this.handleOnChange.bind(this);  
      this.handleOnSubmit = this.handleOnSubmit.bind(this);  
  }  
  handleOnChange(event) {  
      this.setState({result: event.target.value});  
  }  
  handleOnSubmit(event) {  
      alert('You have submitted the input successfully: ' + this.state.result);  
      event.preventDefault();  
  }  
  render() {  
      return (  
          <form onSubmit={this.handleOnSubmit}>  
            <h1>Controlled Form </h1>  
            <label>  
                Full Name:  
                <input type="text" value={this.state.result} onChange={this.handleOnChange} />  
            </label>  
            <input type="submit" value="Submit" />  
         </form>  
      );  
  }  
}  
export default App;  

Now run the application with the npm start command and you can see the form render on the page. Then write the name in the form and click on submit. You can see the success message will pop on the window.

controlled form in react
controlled form in react

Read Components in React js

Form in react js functional component

Here we will see how to create a Form in react js functional component with useRef.

What is a ref in react js?

React generates the actual DOM from your JSX, which the browser renders. By connecting these two representations, Refs enable your React component to access the DOM nodes that serve as its representation.

For example, we will create a form containing two fields username and password, and submit the form, the successful message will pop on the window.

Let’s say the index.html contains the below code

  <div id="root"></div>

The Index.js file is the starting point of the React app, so it contains the below code:

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
    <App />
  
);
reportWebVitals();

The App.js file contains the below code:

import './App.css';
import Form from './Form';
import React, {Component} from "react";
class App extends Component {
	render() {
  	return (
    	<div className='App'>
        <Form />
    	</div>
    );
  }	
}

export default App;

The Form.js file contains the below code:

import React from "react";

const Form = () => {

  const usernameRef = React.useRef();
  const passwordRef = React.useRef();

  const handleOnSubmit = () => {
    console.log('username :' + usernameRef.current.value, 'password :' + passwordRef.current.value);
    alert("username and password successfully submitted")
  };

  return (
    <>
      <form onSubmit={handleOnSubmit}>
        <h1>Fill the Form </h1>
        <label>
          Username:
          <input ref={usernameRef} />
        </label>
        <br />
        <label>
          Password:
          <input ref={passwordRef} />
        </label>
        <br />
        <input type="submit" value="Submit" className="button" / >
      </form>
    </>
  );
};
export default Form;

Now run the application with the npm start command, and you can see the form render on the page. Then fill out the form and click on Submit, you can see the successful message will pop on the window.

Form in react js functional component
Form in react js functional component

Form in react js hooks

Here we will see how to create forms using React js hooks.

As we know, Hooks provide a way to handle stateful logic in functional components, while also providing a way to share non-UI logic and behavior across your application.

For example, we will create a form that will take two inputs, i.e. Full name and password with React hooks.

Let’s say the index.html contains the below code

  <div id="root"></div>

The Index.js file is the starting point of the React app, so it contains the below code:

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
    <App />
  
);
reportWebVitals();

The App.js file contains the below code:

import './App.css';
import Form from './Form';
import React, {Component} from "react";
class App extends Component {
	render() {
  	return (
    	<div className='App'>
        <Form />
    	</div>
    );
  }	
}

export default App;

The Form.js file contains the below code:

import React, { useState } from "react";
function Form() {
  const [fullname, setFullname] = useState("");
  const [email, setEmail] = useState("");

  function handleSubmit() {
    alert("Form submit successfully")
  }
  return (
    <>
    <h2>Fill the Form</h2>
      <form onSubmit={handleSubmit}>
        <label> Full name:
          <input
            type="text"
            name="name"
            value={fullname}
            onChange={(e) => setFullname(e.target.value)}
            required
          /> 
        </label>
        <br />
        <label> Email:
          <input
            type="email"
            name="email"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            required
          />
        </label>
        <br />
        <input type="submit" value="Submit" />
      </form>
      <h3>{"Name value: " + fullname}</h3>
      <h3>{"Email value: " + email}</h3>
    </>
  );
}
export default Form;

Now run the application with the npm start command and you can see the form render on the page. Fill out the form and render and click on the submit button, then you can see the success message will pop on the window.

Form in react js hooks
Form in react js hooks

Read How to upload file in react js?

Dynamic forms in react js

Here we will see how to create dynamic forms in React js.

For example, we will create two fields in the form, which is static, and we will make these two field dynamic. So, the below Form component contains the code that will create a simple form, which contains two fields i.e. name and age.

function Form() {
return (
    <div className="App">
      <form >
     <div >
              <input
                name='name'
                placeholder='Name'
/>
              <input
                name='age'
                placeholder='Age'
             
              />
            </div>
      </form>
    </div>
);
}

export default form;

To make the above two fields dynamic, we will use the React state, so for this, we will create a state known as ‘inputField, which contains, an object i.e. fname and age. Then we will map our form fields based on the state of their inputFields.

Next, we will update the input fields with the values from the inputFields state. So, there will be two values: input.name and input.age. Then we will add an onChange event that will be triggered when we type something into the input fields, by creating ‘handleFormChange()’. After that, we will assign this function as an onChange event to the input fields.

Whereas, the index and event parameters are passed to this onChange event. The index of the array is represented by the index, and the event is represented by the data entered in the input field. Those are passed to the handle or change method.

We will use the spread operator to save our inputFields state in a variable called data (the three dots …). Then, using the index option, we will target the index of the data variable as well as the name of the property.

In the below code, we use event.target.name to specify the index in data and the property name. And we use the event.target.value to store the values from input fields within this data index. We must use the setInputFields method to return this data to the inputFields array.

Furthermore, we will create two buttons i.e, ‘Addmore…’ and Submit. We will create ‘AddMore’ to add more fields to the form. And we will create an addField(), that will run when the button gets clicked.

Now, in the addFields function, we must build an object. And each time we click the button, it will be pushed to the inputFields state, resulting in the creation of a new input field.Then place this newField within the inputFields state.

We will use the Submit button, to see the data when the form is submitted.

We’ll also need a function that will be called when we press this button. It will log the data from the input fields in the terminal. It also includes a method named e.preventDefault() that prevents the page from refreshing.

Let’s say the index.html contains the below code

  <div id="root"></div>

The Index.js file is the starting point of the React app, so it contains the below code:

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
    <App />
  
);
reportWebVitals();

The App.js file contains the below code:

import './App.css';
import Form from './Form';
import React, {Component} from "react";
class App extends Component {
	render() {
  	return (
    	<div className='App'>
        <Form />
    	</div>
    );
  }	
}

export default App;

The Form.js file contains the below code:

import { useState } from 'react';


function Form() {
  const [inputField, setInputField] = useState([
    { name: '', age: '' }
  ])

  const handleFormChange = (index, event) => {
    let data = [...inputField];
    data[index][event.target.name] = event.target.value;
    setInputField(data);
 }
const addNewFields = () => {
    let newfield = { name: '', age: '' }

    setInputField([...inputField, newfield])
}

const handleSubmit = (e) => {
    e.preventDefault();
    console.log(inputField)
}
  return (
    <div className="App">
      <form onSubmit={handleSubmit}>
        {inputField.map((input, index) => {
          return (
            <div key={index}>
              <input
                name='name'
                placeholder='Name'
                value={input.name}
                onChange={event => handleFormChange(index, event)}
              />
              <input
                name='age'
                placeholder='Age'
                value={input.age}
                onChange={event => handleFormChange(index, event)}
              />
            </div>
           
          )
        })}
        <button onClick={addNewFields}>Add More..</button>
        <button onClick={handleSubmit}>Submit</button>
      </form>
    </div>
  );
}

export default Form;

Now run the application, with the npm start command and you can see the Form render on the page, with two buttons. By clicking on Add more icon you can add fields to the Form.

Dynamic forms in react js
Dynamic forms in react js

Now click on the submit button after filling in the data, and you can see the data in the console.

react js Dynamic forms
react js Dynamic forms

Conclusion

This react js tutorial provides you with basic information, like what is Form in react js is, and how to create react js forms in 2 different ways. Also, we saw how we can create a Dynamic form in React js. The content discussed is listed below:

  • What is Forms in react js
  • Ways to create Forms in React js
  • Form in react js functional component
  • Form in react js hooks
  • How to build dynamic forms in react js
  • Form in react js with validation
  • Multiple forms in react js

You may like the following react js tutorials:

>