React Forms and Controlled Inputs

Forms in React

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.

Example Form in JSX

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

Controlled inputs are input fields whose values are managed by React state. This ensures synchronization between the UI and the component state.

Steps to Create a Controlled Input

  1. Create a state variable.
  2. const [name, setName] = useState('');
  3. Assign the state variable to the value attribute of the input.
  4. <input id='name' type='text' value={name} />
  5. Add an onChange event handler to update the state.
  6. 
     setName(e.target.value)}
      value={name} 
    />
            

Handling Events Properly

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)} />

Complete Example: Controlled Input Form

Here is a complete example of a form with controlled inputs:


const FormWithControlledInput = () => {
  const [name, setName] = useState('');

  return (
    
{e.preventDefault(); setName('')}}> setName(e.target.value)} placeholder="Type something!" />
); };

Clicking submit clears the input field by resetting the name state to an empty string.

Benefits of Controlled Inputs

Further Exploration

To continue learning, visit:

Conclusion

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.