Skip to content
- Tutorials
- Courses
- Go Premium
-
React Forms
Last Updated :
12 Aug, 2025
In React, forms are used to take input from users, like text, numbers, or selections. They work just like HTML forms but are often controlled by React state so you can easily track and update the input values.
Example:
JavaScript
import React, { useState } from 'react';
function MyForm() {
const [name, setName] = useState('');
const handleSubmit = (e) => {
e.preventDefault();
alert(`Hello, ${name}`);
};
return (
<form onSubmit={handleSubmit}>
<input
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="Enter your name"
/>
<button type="submit">Submit</button>
</form>
);
}
export default MyForm;
Output:
Forms in React can be easily added as a simple react element. Here are some examples.
Example: This example displays the text input value on the console window when the React onChange event triggers.
JavaScript
// Filename - src/index.js:
import React from "react";
import ReactDOM from "react-dom";
class App extends React.Component {
onInputChange(event)
{
console.log(event.target.value);
}
render()
{
return (<div><form><label>Enter text<
/label>
<input type="text"
onChange={this.onInputChange}/>
</form>
</div>);
}
}
ReactDOM.render(<App />, document.querySelector("#root"));
Output:
Adding Forms in ReactIn HTML the HTML DOM handles the input data but in react the values are stored in state variable and form data is handled by the components.
Example: This example shows updating the value of inputValue each time user changes the value in the input field by calling the setState() function.
JavaScript
// Filename - index.js
import React from "react";
import ReactDOM from "react-dom";
class App extends React.Component {
state = {inputValue : ""};
render()
{
return (
<div><form><label>Enter text<
/label>
<input type="text"
value={this.state.inputValue}
onChange={(e) => this.setState(
{ inputValue: e.target.value })} />
</form>
<br />
<div>Entered Value:
{this.state
.inputValue}</div>
</div>);
}
}
ReactDOM.render(<App />, document.querySelector("#root"));
Output
The submit action in React form is done by using the event handler onSubmit which accepts the submit function.
Example: Here we just added the React onSubmit event handler which calls the function onFormSubmit and it prevents the browser from submitting the form and reloading the page and changing the input and output value to 'Hello World!'.
JavaScript
// Filename - index.js
import React from "react";
import ReactDOM from "react-dom";
class App extends React.Component {
state = {inputValue : ""};
onFormSubmit = (event) => {
event.preventDefault();
this.setState({inputValue : "Hello World!"});
};
render()
{
return (
<div><form onSubmit = {this.onFormSubmit}>
<label>Enter text<
/label>
<input
type="text"
value={this.state.inputValue}
onChange={(e) =>
this.setState({
inputValue: e.target.value,
})
}
/>
</form>
<br />
<div>Entered Value:
{this.state
.inputValue}</div>
</div>);
}
}
ReactDOM.render(<App />, document.querySelector("#root"));
Output
Submitting React FormsIt allows to handle multiple inputs in a single form. Other types of input fields present in Forms are
Textarea
The textarea tag defines the element by its children i.e., enclosed in the tags. In React we use the value prop instead.
Syntax:
<textarea value={text} onChange={handleChange} />
In the above syntax:
- text: refers to the state variable in which the value is stored
- handleChange: is the function to be executed to update the state when the onChange event triggers.
Select
The select tag defines the element by its children i.e., enclosed in the tags. In React similar to text.area we use the value prop instead.
Syntax:
<select>
<option>
</option>
...
</select>
In the above syntax
- this.state.value: refers to the state variable in which the value is stored
- this.handleChange: is the function to be executed to update the state when the onChange event triggers.
Example: This example demonstrate handling multiple input fields in a single Form component.
JavaScript
// import ReactDOM from 'react-dom/client';
import "./index.css";
import React from "react";
// import App from './App';
// import reportWebVitals from './reportWebVitals';
// Filename - index.js
import ReactDOM from "react-dom";
class App extends React.Component {
state = {username : "", email: ""};
onFormSubmit = (event) => {
event.preventDefault();
this.setState({
username : "gfg123",
email : "abc@gfg.org",
});
};
render()
{
return (
<div
style={{
margin: "auto", marginTop: "20px",
textAlign: "center",
}}
>
<form onSubmit={this.onFormSubmit}>
<label> Enter username: </label>
<input
type="text"
value={this.state.username}
onChange={(e) =>
this.setState((prev) => ({
...prev,
username: e.target.value,
}))
}
/>
<br />
<br />
<label>Enter Email Id:</label>
<input
type="email"
value={this.state.email}
onChange={(e) =>
this.setState((prev) => ({
...prev,
email: e.target.value,
}))
}
></input>
<br />
<br />
<input type="submit" value={
"Submit"} />
</form>
<br />
<div>
Entered Value: {this.state.username}
</div>
</div>
);
}
}
const root
= ReactDOM.createRoot(document.getElementById("root"));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
Controlled Vs UnControlled Components
Feature | Controlled Components | UnControlled Components |
---|
Data Source | React state | DOM(internal State) |
---|
Value Binding | value prop bound to state | No binding value uses default value |
---|
How to Access Value | From state Variable | Via ref or document.querySelector |
---|
State Management | Managed by React | Managed by DOM |
---|
Real Time Validation | Easy to implement (validation on onChange ) | Harder, needs manual checks |
---|
Re-rendering | Harder, needs manual checks | Fewer re-renders |
---|
Ease of Debugging | Easier to debug and test | Slightly harder to debug |
---|
Use Case | When you need to track and control user input | For quick/simple forms where state tracking isn’t needed |
---|
Comparison between controlled components vs un controlled componentsNote: It clearly shows that controlled components generally score higher in areas like data source, value binding, and validation. Uncontrolled components perform slightly better in fewer areas such as re-rendering and ease of debugging.
Similar Reads
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
React Fundamentals
React IntroductionReactJS is a component-based JavaScript library used to build dynamic and interactive user interfaces. It simplifies the creation of single-page applications (SPAs) with a focus on performance and maintainability. "Hello, World!" Program in ReactJavaScriptimport React from 'react'; function App() {
6 min read
React Environment SetupTo run any React application, we need to first setup a ReactJS Development Environment. In this article, we will show you a step-by-step guide to installing and configuring a working React development environment.Pre-requisite:We must have Nodejs installed on our PC. So, the very first step will be
3 min read
React JS ReactDOMReactDOM is a core React package that provides DOM-specific methods to interact with and manipulate the Document Object Model (DOM), enabling efficient rendering and management of web page elements. ReactDOM is used for: Rendering Components: Displays React components in the DOM.DOM Manipulation: Al
2 min read
React JSXJSX stands for JavaScript XML, and it is a special syntax used in React to simplify building user interfaces. JSX allows you to write HTML-like code directly inside JavaScript, enabling you to create UI components more efficiently. Although JSX looks like regular HTML, itâs actually a syntax extensi
5 min read
ReactJS Rendering ElementsIn this article we will learn about rendering elements in ReactJS, updating the rendered elements and will also discuss about how efficiently the elements are rendered.What are React Elements?React elements are the smallest building blocks of a React application. They are different from DOM elements
3 min read
React ListsIn lists, React makes it easier to render multiple elements dynamically from arrays or objects, ensuring efficient and reusable code. Since nearly 85% of React projects involve displaying data collectionsâlike user profiles, product catalogs, or tasksâunderstanding how to work with lists.To render a
4 min read
React FormsIn React, forms are used to take input from users, like text, numbers, or selections. They work just like HTML forms but are often controlled by React state so you can easily track and update the input values.Example:JavaScriptimport React, { useState } from 'react'; function MyForm() { const [name,
4 min read
ReactJS KeysA key serves as a unique identifier in React, helping to track which items in a list have changed, been updated, or removed. It is particularly useful when dynamically creating components or when users modify the list. When rendering a list, you need to assign a unique key prop to each element in th
4 min read
Components in React
React Lifecycle In React, the lifecycle refers to the various stages a component goes through. These stages allow developers to run specific code at key moments, such as when the component is created, updated, or removed. By understanding the React lifecycle, you can better manage resources, side effects, and perfo
7 min read
React Hooks
Routing in React
Advanced React Concepts
React Projects
`;
$(commentSectionTemplate).insertBefore(".article--recommended");
}
loadComments();
});
});
function loadComments() {
if ($("iframe[id*='discuss-iframe']").length top_of_element && top_of_screen articleRecommendedTop && top_of_screen articleRecommendedBottom)) {
if (!isfollowingApiCall) {
isfollowingApiCall = true;
setTimeout(function(){
if (loginData && loginData.isLoggedIn) {
if (loginData.userName !== $('#followAuthor').val()) {
is_following();
} else {
$('.profileCard-profile-picture').css('background-color', '#E7E7E7');
}
} else {
$('.follow-btn').removeClass('hideIt');
}
}, 3000);
}
}
});
}
$(".accordion-header").click(function() {
var arrowIcon = $(this).find('.bottom-arrow-icon');
arrowIcon.toggleClass('rotate180');
});
});
window.isReportArticle = false;
function report_article(){
if (!loginData || !loginData.isLoggedIn) {
const loginModalButton = $('.login-modal-btn')
if (loginModalButton.length) {
loginModalButton.click();
}
return;
}
if(!window.isReportArticle){
//to add loader
$('.report-loader').addClass('spinner');
jQuery('#report_modal_content').load(gfgSiteUrl+'wp-content/themes/iconic-one/report-modal.php', {
PRACTICE_API_URL: practiceAPIURL,
PRACTICE_URL:practiceURL
},function(responseTxt, statusTxt, xhr){
if(statusTxt == "error"){
alert("Error: " + xhr.status + ": " + xhr.statusText);
}
});
}else{
window.scrollTo({ top: 0, behavior: 'smooth' });
$("#report_modal_content").show();
}
}
function closeShareModal() {
const shareOption = document.querySelector('[data-gfg-action="share-article"]');
shareOption.classList.remove("hover_share_menu");
let shareModal = document.querySelector(".hover__share-modal-container");
shareModal && shareModal.remove();
}
function openShareModal() {
closeShareModal(); // Remove existing modal if any
let shareModal = document.querySelector(".three_dot_dropdown_share");
shareModal.appendChild(Object.assign(document.createElement("div"), { className: "hover__share-modal-container" }));
document.querySelector(".hover__share-modal-container").append(
Object.assign(document.createElement('div'), { className: "share__modal" }),
);
document.querySelector(".share__modal").append(Object.assign(document.createElement('h1'), { className: "share__modal-heading" }, { textContent: "Share to" }));
const socialOptions = ["LinkedIn", "WhatsApp","Twitter", "Copy Link"];
socialOptions.forEach((socialOption) => {
const socialContainer = Object.assign(document.createElement('div'), { className: "social__container" });
const icon = Object.assign(document.createElement("div"), { className: `share__icon share__${socialOption.split(" ").join("")}-icon` });
const socialText = Object.assign(document.createElement("span"), { className: "share__option-text" }, { textContent: `${socialOption}` });
const shareLink = (socialOption === "Copy Link") ?
Object.assign(document.createElement('div'), { role: "button", className: "link-container CopyLink" }) :
Object.assign(document.createElement('a'), { className: "link-container" });
if (socialOption === "LinkedIn") {
shareLink.setAttribute('href', `https://www.linkedin.com/sharing/share-offsite/?url=${window.location.href}`);
shareLink.setAttribute('target', '_blank');
}
if (socialOption === "WhatsApp") {
shareLink.setAttribute('href', `https://api.whatsapp.com/send?text=${window.location.href}`);
shareLink.setAttribute('target', "_blank");
}
if (socialOption === "Twitter") {
shareLink.setAttribute('href', `https://twitter.com/intent/tweet?url=${window.location.href}`);
shareLink.setAttribute('target', "_blank");
}
shareLink.append(icon, socialText);
socialContainer.append(shareLink);
document.querySelector(".share__modal").appendChild(socialContainer);
//adding copy url functionality
if(socialOption === "Copy Link") {
shareLink.addEventListener("click", function() {
var tempInput = document.createElement("input");
tempInput.value = window.location.href;
document.body.appendChild(tempInput);
tempInput.select();
tempInput.setSelectionRange(0, 99999); // For mobile devices
document.execCommand('copy');
document.body.removeChild(tempInput);
this.querySelector(".share__option-text").textContent = "Copied"
})
}
});
// document.querySelector(".hover__share-modal-container").addEventListener("mouseover", () => document.querySelector('[data-gfg-action="share-article"]').classList.add("hover_share_menu"));
}
function toggleLikeElementVisibility(selector, show) {
document.querySelector(`.${selector}`).style.display = show ? "block" : "none";
}
function closeKebabMenu(){
document.getElementById("myDropdown").classList.toggle("show");
}