In React, a component’s internal state is kept to minimum because every time the state changes, the component is rendered again. The purpose of this is to have an accurate representation of the component state in your JavaScript code and let React keep the interface in sync.

For this reason, form components such as <input>, <textarea>, and <option> differ from their HTML counterparts because they can be mutated via user interactions.

React provides two ways of handling forms as components and lets you choose based on your app characteristics or personal preference. The two available ways to handle a form field are as a controlled component or an uncontrolled component.

Controlled Components

A form component with a value or checked prop is called a controlled component. In a controlled component, the value rendered inside the element will always reflect the value of the prop. By default the user won’t be able to change it.

import React, { Component } from 'react';
import {render} from 'react-dom';

class Search extends Component {
	constructor() {
		super();
		this.state = {
			searchTerm: "React"
		};
	}
	handleChange(event) {
		this.setState({searchTerm: event.target.value});
	}
	render() {
		return (
			<div>
				Search Term:
				<input type="search" value={this.state.searchTerm}
				onChange={this.handleChange.bind(this)} />
			</div>
		)
	}
}

render(<Search />, document.body);

Special Cases set value in React

<textarea value="This is a description." />


<select value="B">
	<option value="A">Mobile</option>
	<option value="B">Work</option>
	<option value="C">Home</option>
</select>

Uncontrolled Components

Controlled components adhere to React’s principles and have their advantages. While uncontrolled components are an anti-pattern for how most other components are constructed in React, sometimes you don’t need to oversee the user input field by field.

This is especially true in longer forms, where you want to let the user fill in the fields and then process everything when the user is done.

If you want to set up an initial value for an uncontrolled form component, use the defaultValue prop instead of value, or defaultChecked in case of checkbox.

handleSubmit(event) {
	console.log("Submitted values are: ",
	event.target.name.value,
	event.target.email.value);
	event.preventDefault();
}

render() {
	return (
		<form onSubmit={this.handleSubmit}>
			<div className="formGroup">
				Name: <input name="name" type="text" />
			</div>
			<div className="formGroup">
				E-mail: <input name="email" type="mail" />
			</div>
			<button type="submit">Submit</button>
		</form>
	)
}

 

ReactJS: Working with form

Category: Uncategorized
0
5469 views

Join the discussion

Your email address will not be published. Required fields are marked *