- Introduction
In this chapter, we’ll learn about Forms and Controlled Components in React. React allows you to create powerful and efficient forms using controlled components. Let’s dive into a conversation between Geek and Gal to understand how forms and controlled components work together!
In React, forms work a bit differently. Instead of reading values from the DOM, you use
controlled components
to handle form data.
What are controlled components?
Controlled components are form elements where React manages the state, so their values are controlled by React!
To create a controlled component, you need to set the
value
attribute of an input element to the corresponding state property and add an
onChange
event handler to update that state.
Can you show me an example?
Sure! Here's an example of a simple form with a controlled input component:
import React, { useState } from 'react';
function NameForm() {
const [name, setName] = useState('');
function handleChange(event) {
setName(event.target.value);
}
function handleSubmit(event) {
event.preventDefault();
alert('Hello, ' + name + '!');
}
return (
<form onSubmit={handleSubmit}>
<label>
Name:
<input type="text" value={name} onChange={handleChange} />
</label>
<input type="submit" value="Submit" />
</form>
);
}
I see! The input's value is controlled by React's state, and it updates as the user types.
That's right! The
handleChange
function updates the state, and the form submission is handled by the
handleSubmit
function.
How about a funny example of a form and controlled component?
Sure! Let's make a form that asks for your favorite joke!
import React, { useState } from 'react';
function JokeForm() {
const [joke, setJoke] = useState('');
function handleChange(event) {
setJoke(event.target.value);
}
function handleSubmit(event) {
event.preventDefault();
alert('Your favorite joke is: "' + joke + '" 😂');
}
return (
<form onSubmit={handleSubmit}>
<label>
Favorite Joke:
<input type="text" value={joke} onChange={handleChange} />
</label>
<input type="submit" value="Submit" />
</form>
);
}
Haha, that's awesome! A form to submit your favorite joke, and it's a controlled component!
Exactly! Controlled components make it easy to manage form data in React.
- Conclusion
Forms and Controlled Components in React provide a powerful and efficient way to handle form data. By using controlled components, you can easily manage the state of form elements and keep your code clean and maintainable. Remember, controlled components make handling form data a breeze in React! 😄