💡 Learn from AI

React Fundamentals

Forms and Controlled Components

Forms are an essential part of any web application, and React provides various ways to handle forms. In React, forms can be handled using controlled components. A controlled component is a component that renders a form element and controls it by keeping the form data in the component's state. This allows you to have full control over the form data and handle user input in a more efficient manner.

To create a controlled component, you need to create a stateful component and define the input elements as its state. You also need to define an onChange event handler that updates the state whenever the user enters data into the input field. This way, the component's state is always in sync with the form data.

Here is an example of a simple controlled component that handles a text input field:

import React, { Component } from 'react';

class MyForm extends Component {
  state = {
    text: ''
  }

  handleChange = (event) => {
    this.setState({ text: event.target.value });
  }

  handleSubmit = (event) => {
    alert('Text submitted: ' + this.state.text);
    event.preventDefault();
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <label>
          Text:
          <input type='text' value={this.state.text} onChange={this.handleChange} />
        </label>
        <input type='submit' value='Submit' />
      </form>
    );
  }
}

In this example, the MyForm component has a state property called text, which is initialized to an empty string. The handleChange method updates the component's state whenever the user enters text into the input field. The handleSubmit method is called when the form is submitted and displays an alert with the text entered by the user.

For further reading, the official React documentation has a great section on forms and controlled components: https://reactjs.org/docs/forms.html.

Take quiz (4 questions)

Previous unit

Lists and Keys

Next unit

React Hooks

All courses were automatically generated using OpenAI's GPT-3. Your feedback helps us improve as we cannot manually review every course. Thank you!