React.js / React Forms and Validation

Creating Controlled and Uncontrolled Components

In this tutorial, we'll explore how to create controlled and uncontrolled components in React. You'll learn the differences between the two, how they work, and when to use each ty…

Tutorial 3 of 5 5 resources in this section

Section overview

5 resources

Explores handling forms, input, and validation in React applications.

1. Introduction

In this tutorial, we aim to understand how to create Controlled and Uncontrolled Components in React. We will delve deep into their differences, understand how they operate, and learn when to use each type.

By the end of this tutorial, you should be able to:

  • Understand what Controlled and Uncontrolled Components are.
  • Create Controlled and Uncontrolled Components.
  • Understand when to use each type.

Prerequisites

  • Basic understanding of JavaScript.
  • Familiarity with React and its syntax.

2. Step-by-Step Guide

Controlled Components

In React, a controlled component is a component that takes its current value through props and notifies changes through callbacks like onChange. A parent component "controls" it by handling the callback and managing its own state and passing the new values as props to the controlled component.

Example of a Controlled Component:

class ControlledComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {value: ''};

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

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

  handleSubmit(event) {
    alert('A name was submitted: ' + this.state.value);
    event.preventDefault();
  }

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

Uncontrolled Components

Unlike controlled components, uncontrolled components store their own state internally, and you query the DOM using a ref to find its current value when you need it. This is a bit more like traditional HTML.

Example of an Uncontrolled Component:

class UncontrolledComponent extends React.Component {
  constructor(props) {
    super(props);
    this.handleSubmit = this.handleSubmit.bind(this);
    this.input = React.createRef();
  }

  handleSubmit(event) {
    alert('A name was submitted: ' + this.input.current.value);
    event.preventDefault();
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <label>
          Name:
          <input type="text" ref={this.input} />
        </label>
        <input type="submit" value="Submit" />
      </form>
    );
  }
}

3. Code Examples

Controlled Component Example

//This is a Controlled Component
class ControlledComponent extends React.Component {
  state = {
    text: ''
  }

  //Handle change function is used to update the state
  handleChange = (event) => {
    this.setState({ text: event.target.value });
  }

  render() {
    return (
      <input
        type="text"
        value={this.state.text}
        onChange={this.handleChange}
      />
    );
  }
}

In the above example, the input field's value is controlled by the state within the component.

Uncontrolled Component Example

//This is an Uncontrolled Component
class UncontrolledComponent extends React.Component {
  input = React.createRef();

  handleClick = () => {
    alert(this.input.current.value);
  }

  render() {
    return (
      <div>
        <input
          type="text"
          ref={this.input}
        />
        <button onClick={this.handleClick}>Alert the Value!</button>
      </div>
    );
  }
}

In this example, we use ref to "get" the value from the input field.

4. Summary

In this tutorial, we've covered the differences between Controlled and Uncontrolled Components in React. We've learned how to create each type and when to use them. While Controlled Components have more control and predictability, Uncontrolled Components allow more flexibility and are closer to traditional HTML.

To further enhance your skills, you may want to learn more about forms and handling events in React.

5. Practice Exercises

  1. Create a Controlled Component which takes user input and displays it in real time.

  2. Create an Uncontrolled Component which takes user input and displays it when a button is clicked.

Solution

  1. Controlled Component
class ControlledComponent extends React.Component {
  state = {
    text: ''
  }

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

  render() {
    return (
      <div>
        <input
          type="text"
          value={this.state.text}
          onChange={this.handleChange}
        />
        <p>{this.state.text}</p>
      </div>
    );
  }
}
  1. Uncontrolled Component
class UncontrolledComponent extends React.Component {
  input = React.createRef();

  handleClick = () => {
    this.setState({ text: this.input.current.value });
  }

  render() {
    return (
      <div>
        <input
          type="text"
          ref={this.input}
        />
        <button onClick={this.handleClick}>Display Value</button>
        <p>{this.state.text}</p>
      </div>
    );
  }
}

In these exercises, we put into practice what we learned by creating Controlled and Uncontrolled Components. You can enhance your skills further by trying to convert a Controlled Component into an Uncontrolled one and vice versa.

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

JSON Formatter & Validator

Beautify, minify, and validate JSON data.

Use tool

Word to PDF Converter

Easily convert Word documents to PDFs.

Use tool

PDF Password Protector

Add or remove passwords from PDF files.

Use tool

Hex to Decimal Converter

Convert between hexadecimal and decimal values.

Use tool

Markdown to HTML Converter

Convert Markdown to clean HTML.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help