Updated March 18, 2023
Introduction to Forms in React
As we know that forms are an important part of a web application, therefore it is necessary to have knowledge about form designing in react. In this article, we will see what are different type of forms available in react, their syntax and a few examples related to react forms.
Syntax:
class FormClassName extends React.Component {
constructor(props) {
super(props);
// handle initialization activities
}
handleChangeEvents(event) {
//handle change events
}
handleSubmitevents(event) {
// handle submit events
}
render() {
return (
<form onSubmit={this.handleSubmitevents}>
<label>
Name:
<input type="text" value={this.state.value} onChange={this.handleChangeEvents} />
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
The above syntax shows how a form is created to react. It will require creating a class extending React. The component and render method will have a form tag in it. As we can see render contains form tag within which we have a label for showing text followed by input type tag similar to HTML. Here we have specified submit events and change events on button and text respectively.
Types of Forms in React
Basically, there are two types of forms:
1. Controlled Input
A react form is considered to be controlled when a react component that is responsible for rendering is also controlling the form behavior on subsequent inputs. That means whenever values inform changes, the component saves the changed value to its state.
Example:
Code:
import React, { Component } from 'react';
class ControlledForm extends Component {
constructor () {
this.state = {
username: ''
}
}
changeEventHandler = event => {
this.setState({
username: event.target.value
});
}
render () {
return (
<form>
<input type="username"
name="username"
value={this.state.username}
onChange={this.changeEventHandler}
/>
</form>
);
}
}
export default ControlledForm;
In the above example each time value of username changes, the change event handler is called and its updated value is saved to state. Therefore controlled form can be used for applying validations, disabling a button until a text field contains some text, etc.
2. Uncontrolled Forms
Uncontrolled forms are similar to HTML forms. This does not make use of any listener. This required to get the value of the field at the required time for example on click of a button. The required value is read using a reference associated with the form elements. This is how the reference is defined.
Code:
<form onSubmit={this.submitHandler}>
<div>
<input type="text" value="valueref" ref="valueref" />
</div>
</form>
“valueref” used above is used to read the value of the field like.
Code:
this.refs.valueref.value
Now, we have a clear understanding of controlled and uncontrolled forms to react.
Examples of Forms in React
Given below are the examples mentioned:
Example #1
To start things we will use a simple text field in our form. Here is a code showing a text field to enter a username.
Code:
import React from 'react';
import ReactDOM from 'react-dom';
class TestForm extends React.Component {
render() {
return (
<form>
<h1>Hello</h1>
<p>Please Enter your UserName:</p>
<input
type="text"
/>
</form>
);
}
}
ReactDOM.render(<TestForm />, document.getElementById('root'));
Output:
Example #2
Now we will see another example showing how a text field is used with a submit button and how to handle events related to click of a button.
Code:
import React from 'react';
import ReactDOM from 'react-dom';
class TestForm extends React.Component {
constructor(props) {
super(props);
this.state = { username: '' };
}
submitmyeventHandler = (myevent) => {
alert("You are submitting " + this.state.username);
}
changeEventHandler = (myevent) => {
this.setState({username: myevent.target.value});
}
render() {
return (
<form onSubmit={this.submitmyeventHandler}>
<h1>Hello {this.state.username}</h1>
<p>Please Enter your user name, and click submit:</p>
<input
type='text'
onChange={this.changeEventHandler}
/>
<input
type='submit'
/>
</form>
);
}
}
ReactDOM.render(<TestForm />, document.getElementById('root'));
Output:
When the user name is entered, listeners will be triggered and the header will change dynamically.
After clicking the submit button, the submit event will be triggered and an alert will be displayed like the one attached below.
Example #3
In this example, we will see how multiple fields are used in a form. Here we have two fields for entering firstName and lastName. We have used a change event handler in order to dynamically change the content of a text with a change in their respective values.
Code:
import React from 'react';
import ReactDOM from 'react-dom';
class TestForm extends React.Component {
constructor(props) {
super(props);
this.state = {
firstName: '',
lastName: null,
};
}
changeEventHandler = (event) => {
let nam = event.target.name;
let val = event.target.value;
this.setState({[nam]: val});
}
render() {
return (
<form>
<h1>Welcome {this.state.firstName} {this.state.lastName}</h1>
<p>Enter first Name:</p>
<input
type='text'
name='firstName'
onChange={this.changeEventHandler}
/>
<p>Enter Last Name:</p>
<input
type='text'
name='lastName'
onChange={this.changeEventHandler}
/>
</form>
);
}
}
ReactDOM.render(<TestForm />, document.getElementById('root'));
The below-attached output shows two text fields for entering the first name and last name. With the change in the content of the first name and last name, the above-placed header is changed.
Output:
Conclusion
Apart from the above examples, we can provide more customizations to forms as per our needs. The form is an important react component and is meant to be reusable.
Recommended Articles
This is a guide to Forms in React. Here we discuss the basic concept and types of forms in react along with its examples and code implementation. You may also look at the following articles to learn more –