Forms are essential to React applications as they enable user interaction. Users can enter data, make selections, and submit forms. This user input can be processed, stored, or sent to a backend.
Forms in JSX work similarly to HTML forms. A typical form contains elements like <label>, <input>, <select>, and <textarea>, enclosed within a <form> tag. The form typically includes a <button> for submission.
Here is a basic form in JSX:
Note: JSX uses htmlFor instead of HTML's for, since for is a reserved word in JavaScript.
Controlled inputs are input fields whose values are managed by React state. This ensures synchronization between the UI and the component state.
const [name, setName] = useState('');
value attribute of the input.<input id='name' type='text' value={name} />
onChange event handler to update the state.
setName(e.target.value)}
value={name}
/>
Event handlers should be passed as references, not invoked directly. If arguments are required, use an anonymous function.
Do NOT invoke my onClick callback!
changeFunc(e.target.value)} />
Here is a complete example of a form with controlled inputs:
const FormWithControlledInput = () => {
const [name, setName] = useState('');
return (
);
};
Clicking submit clears the input field by resetting the name state to an empty string.
To continue learning, visit:
React forms and controlled inputs provide a structured way to handle user input. Using controlled inputs ensures that form data is always in sync with state, making validation and updates seamless.