Skip to main content

Controlled Forms in React (Live Playground)

Controlled forms are an essential concept in React, as they allow you to manage user input using state and event handlers. In this tutorial, we'll explore how to create and manage controlled forms in React with sample code and simple explanations.

Creating a Controlled Form

Controlled forms rely on React state to manage the form inputs. Let's create a controlled form with a single input field:

JavaScript
import React, { useState } from 'react';

function ControlledForm() {
const [name, setName] = useState('');

const handleChange = event => {
setName(event.target.value);
};

const handleSubmit = event => {
event.preventDefault();
console.log(`Form submitted with: ${name}`);
};

return (
<form onSubmit={handleSubmit}>
<input value={name} onChange={handleChange} />
<button type="submit">Submit</button>
</form>
);
}

export default ControlledForm;

In this example, we have an input field with its value controlled by the name state variable. The handleChange function updates the name state when the user types in the input field. The form's onSubmit event handler, handleSubmit, prevents the default form submission behavior and logs the submitted value.

Live Playground, Try it Yourself

Managing Multiple Inputs

To manage multiple input fields in a controlled form, you can use a single state object:

JavaScript
import React, { useState } from 'react';

function ControlledForm() {
const [formData, setFormData] = useState({
firstName: '',
lastName: '',
});

const handleChange = event => {
const { name, value } = event.target;
setFormData(prevFormData => ({ ...prevFormData, [name]: value }));
};

const handleSubmit = event => {
event.preventDefault();
console.log(`Form submitted with: ${JSON.stringify(formData)}`);
};

return (
<form onSubmit={handleSubmit}>
<input name="firstName" value={formData.firstName} onChange={handleChange} />
<input name="lastName" value={formData.lastName} onChange={handleChange} />
<button type="submit">Submit</button>
</form>
);
}

export default ControlledForm;

In this example, we have two input fields, firstName and lastName. The handleChange function updates the appropriate property in the formData state object based on the input's name attribute.

Live Playground, Try it Yourself

Conclusion

Controlled forms are crucial for managing user input in React applications. By understanding how to create controlled forms and manage multiple input fields using state and event handlers, you'll be better equipped to handle user interactions in your React projects. With a strong foundation in controlled forms, you'll be well on your way to becoming an effective React developer.