Middle
What does a controlled input look like in React?
sobes.tech AI
Answer from AI
A controlled input in React is a form element whose value is fully managed by the component's state. The input's value is stored in the state, and changes to the input are handled through an event handler that updates the state.
Example of a controlled input:
import React, { useState } from 'react';
function ControlledInput() {
const [value, setValue] = useState('');
const handleChange = (event) => {
setValue(event.target.value);
};
return (
<input type="text" value={value} onChange={handleChange} />
);
}
Here, value of the input always matches the value state in the component, and any text change triggers handleChange, which updates the state. This allows React to control and synchronize the form's state.