In React, a controlled input is an input element whose value is controlled by the component's state. This means that the value of the input is set and updated by the component's code. When the user interacts with the input (e.g. types in a text field), the component's state is updated with the new value, and the input's value is updated accordingly.
On the other hand, an uncontrolled input is an input element whose value is managed by the DOM itself. In this case, the component's code does not directly set or update the input's value. Instead, the value of the input is determined by the user's interactions with the input element.
Controlled input example:
import React, { useState } from 'react';
function ControlledInputExample() {
const [inputValue, setInputValue] = useState('');
function handleInputChange(event) {
setInputValue(event.target.value);
}
return (
<div>
<label>
Controlled Input:
<input type="text" value={inputValue} onChange={handleInputChange} />
</label>
<p>You typed: {inputValue}</p>
</div>
);
}
In this example, we're using React's useState
hook to create a state variable called inputValue
. We're also defining a function called handleInputChange
that will update the inputValue
state whenever the user types in the input field. The input element has a value
prop that is set to inputValue
, and an onChange
prop that is set to handleInputChange
. This makes the input a controlled input, as its value is controlled by the state of the component.
Uncontrolled input example:
import React from 'react';
function UncontrolledInputExample() {
function handleSubmit(event) {
event.preventDefault();
const formData = new FormData(event.target);
const inputValue = formData.get('input');
console.log('Uncontrolled Input:', inputValue);
}
return (
<div>
<form onSubmit={handleSubmit}>
<label>
Uncontrolled Input:
<input type="text" name="input" />
</label>
<button type="submit">Submit</button>
</form>
</div>
);
}
In this example, we're using an uncontrolled input. The component does not have any state to control the value of the input. Instead, we're using the FormData
API to get the value of the input when the form is submitted. The input element does not have a value
prop or an onChange
prop. The value of the input is managed entirely by the DOM, and is not controlled by the component's code.