• 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!
Gal Normal

In React, forms work a bit differently. Instead of reading values from the DOM, you use controlled components to handle form data.

Geek Curious

What are controlled components?

Gal Happy

Controlled components are form elements where React manages the state, so their values are controlled by React!

  • Controlled Components
Gal Pleased

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.

Geek Curious

Can you show me an example?

Gal Happy

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>
  );
}
Geek Happy

I see! The input's value is controlled by React's state, and it updates as the user types.

Gal Happy

That's right! The handleChange function updates the state, and the form submission is handled by the handleSubmit function.

  • Hilarious Example
Geek Curious

How about a funny example of a form and controlled component?

Gal Pleased

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>
  );
}
Geek Happy

Haha, that's awesome! A form to submit your favorite joke, and it's a controlled component!

Gal Happy

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! 😄