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 : "[email protected]",
});
};
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.