ReactJS - Controlled Components: A Beginner's Guide

Hello there, future React developers! Today, we're going to embark on an exciting journey into the world of Controlled Components in ReactJS. Don't worry if you're new to programming – I'll be your friendly guide, and we'll take this step by step. By the end of this tutorial, you'll be creating forms like a pro!

ReactJS - Controlled Component

What Are Controlled Components?

Before we dive in, let's start with a simple analogy. Imagine you're at a fancy restaurant, and you want to order a custom pizza. In this scenario, you (the React component) are in control of what goes on the pizza (the form data). Every time you want to add or remove a topping, you tell the waiter (the state), and they update your order accordingly. This is essentially how controlled components work in React!

In React terms, a controlled component is an input form element whose value is controlled by React. Instead of the DOM handling the form data, React takes charge.

Why Use Controlled Components?

  1. Single Source of Truth: All form data is stored in the component state.
  2. Immediate Access to Input: You can access input values right away.
  3. More Control: You can easily manipulate and validate input data.

Now, let's get our hands dirty with some code!

Controlled Component With Single Input

Let's start with a simple example – a text input field that greets the user.

import React, { useState } from 'react';

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

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

return (
<div>
<input type="text" value={name} onChange={handleChange} />
<p>Hello, {name}!</p>
</div>
);
}

export default GreetingInput;

Let's break this down:

  1. We import useState from React to manage our component's state.
  2. We create a state variable name and its setter function setName.
  3. The handleChange function updates the name state whenever the input changes.
  4. In the JSX, we set the input's value to name and attach the onChange event to handleChange.
  5. We display a greeting using the current value of name.

This is the essence of a controlled component – React controls the input's value through state.

Try It Yourself!

Go ahead and type your name in the input field. Notice how the greeting updates instantly? That's the magic of controlled components!

Creating a Simple Form

Now that we've got the basics down, let's create a more complex form with multiple inputs.

import React, { useState } from 'react';

function PizzaOrderForm() {
const [order, setOrder] = useState({
name: '',
size: 'medium',
toppings: []
});

const handleChange = (event) => {
const { name, value, type, checked } = event.target;

if (type === 'checkbox') {
if (checked) {
setOrder(prevOrder => ({
...prevOrder,
toppings: [...prevOrder.toppings, value]
}));
} else {
setOrder(prevOrder => ({
...prevOrder,
toppings: prevOrder.toppings.filter(topping => topping !== value)
}));
}
} else {
setOrder(prevOrder => ({
...prevOrder,
[name]: value
}));
}
};

const handleSubmit = (event) => {
event.preventDefault();
alert(`Order placed! Name: ${order.name}, Size: ${order.size}, Toppings: ${order.toppings.join(', ')}`);
};

return (
<form onSubmit={handleSubmit}>
<input
type="text"
name="name"
value={order.name}
onChange={handleChange}
placeholder="Your Name"
/>
<select name="size" value={order.size} onChange={handleChange}>
<option value="small">Small</option>
<option value="medium">Medium</option>
<option value="large">Large</option>
</select>
<label>
<input
type="checkbox"
name="toppings"
value="cheese"
checked={order.toppings.includes('cheese')}
onChange={handleChange}
/>
Cheese
</label>
<label>
<input
type="checkbox"
name="toppings"
value="pepperoni"
checked={order.toppings.includes('pepperoni')}
onChange={handleChange}
/>
Pepperoni
</label>
<button type="submit">Place Order</button>
</form>
);
}

export default PizzaOrderForm;

Wow, that's a lot of code! But don't worry, we'll break it down step by step:

  1. We create a state object order that holds all our form data.
  2. The handleChange function is more complex now. It handles different input types:
  • For text and select inputs, it updates the corresponding property in the state.
  • For checkboxes, it adds or removes toppings from the array.
  1. We have a handleSubmit function that prevents the default form submission and shows an alert with the order details.
  2. In the JSX, we create inputs for name, size (as a select), and toppings (as checkboxes).
  3. Each input's value (or checked state for checkboxes) is controlled by the order state.

The Power of Controlled Forms

With this setup, you have complete control over your form data. Want to add validation? Easy! Just modify the handleChange function. Need to transform the data before submission? Just update the handleSubmit function. The possibilities are endless!

Common Methods for Controlled Components

Let's summarize some common methods used with controlled components:

Method Description
useState Hook for managing component state
onChange Event handler for input changes
onSubmit Event handler for form submission
preventDefault Prevents default form submission behavior
event.target.value Retrieves the current value of an input
event.target.checked Retrieves the checked state of a checkbox

Conclusion

Congratulations! You've just learned about controlled components in React. We've covered single inputs, complex forms, and even created a pizza order form (I'm getting hungry just thinking about it!).

Remember, controlled components give you the power to manage form data with precision. It might seem like more work at first, but the control and flexibility you gain are well worth it.

As you continue your React journey, you'll find countless ways to use controlled components. Maybe you'll create a blog post editor, a user registration form, or even a pizza delivery app (if you do, please send me a discount code!).

Keep practicing, stay curious, and happy coding!

以下是繁體中文的翻譯:

ReactJS - Controlled Components:初學者指南

你好,未來的React開發者!今天,我們將踏上一段令人興奮的旅程,探索ReactJS中的Controlled Components。如果你是編程新手,別擔心——我將成為你的友好導遊,我們會一步步來。在本教程結束時,你將能夠像專業人士一樣創建表單!

Controlled Components是什麼?

在我們深入之前,讓我們從一個簡單的比喻開始。想像你在一間豪華餐廳,你想點一個自定義披薩。在這個情景中,你(React組件)控制著披薩上放些什麼(表單數據)。每當你想添加或刪除配料時,你告訴服務員(狀態),他們會相應地更新你的訂單。這基本上就是React中Controlled Components的工作原理!

在React術語中,Controlled Component是一個其值由React控制的表單輸入元素。與DOM處理表單數據不同,React負責控制。

為什麼使用Controlled Components?

  1. 唯一的真理來源:所有表單數據都存儲在組件狀態中。
  2. 立即訪問輸入:你可以立即訪問輸入值。
  3. 更多控制:你可以輕鬆操縱和驗證輸入數據。

現在,讓我們來動手寫一些代碼!

帶有單個輸入的Controlled Component

讓我們從一個簡單的例子開始——一個向用戶問候的文本輸入字段。

import React, { useState } from 'react';

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

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

return (
<div>
<input type="text" value={name} onChange={handleChange} />
<p>Hello, {name}!</p>
</div>
);
}

export default GreetingInput;

讓我們分解一下:

  1. 我們從React導入useState以管理組件狀態。
  2. 我們創建了一個狀態變量name及其設置函數setName
  3. handleChange函數在輸入更改時更新name狀態。
  4. 在JSX中,我們將輸入的value設為name並將onChange事件绑定到handleChange
  5. 我們使用name的當前值顯示問候。

這就是Controlled Component的本質——React通過狀態控制輸入的值。

試著自己動手!

在輸入字段中輸入你的名字。注意問候是如何立即更新的?這就是Controlled Components的魔法!

創建一個簡單的表單

現在我們已經掌握了基本知識,讓我們創建一個帶有多个輸入的更複雜的表單。

import React, { useState } from 'react';

function PizzaOrderForm() {
const [order, setOrder] = useState({
name: '',
size: 'medium',
toppings: []
});

const handleChange = (event) => {
const { name, value, type, checked } = event.target;

if (type === 'checkbox') {
if (checked) {
setOrder(prevOrder => ({
...prevOrder,
toppings: [...prevOrder.toppings, value]
}));
} else {
setOrder(prevOrder => ({
...prevOrder,
toppings: prevOrder.toppings.filter(topping => topping !== value)
}));
}
} else {
setOrder(prevOrder => ({
...prevOrder,
[name]: value
}));
}
};

const handleSubmit = (event) => {
event.preventDefault();
alert(`訂單已下!名字:${order.name},大小:${order.size},配料:${order.toppings.join(', ')}`);
};

return (
<form onSubmit={handleSubmit}>
<input
type="text"
name="name"
value={order.name}
onChange={handleChange}
placeholder="你的名字"
/>
<select name="size" value={order.size} onChange={handleChange}>
<option value="small">小</option>
<option value="medium">中</option>
<option value="large">大</option>
</select>
<label>
<input
type="checkbox"
name="toppings"
value="cheese"
checked={order.toppings.includes('cheese')}
onChange={handleChange}
/>
起司
</label>
<label>
<input
type="checkbox"
name="toppings"
value="pepperoni"
checked={order.toppings.includes('pepperoni')}
onChange={handleChange}
/>
肉醬
</label>
<button type="submit">下訂單</button>
</form>
);
}

export default PizzaOrderForm;

哇,這可是相當多的代碼!但別擔心,我們會一步步分解:

  1. 我們創建了一個狀態對象order,它包含了所有的表單數據。
  2. handleChange函數現在更複雜了。它處理不同的輸入類型:
  • 對於文本和選擇輸入,它更新對應的狀態屬性。
  • 對於複選框,它從數組中添加或刪除配料。
  1. 我們有一個handleSubmit函數,它阻止默認的表單提交並顯示訂單詳情的彈窗。
  2. 在JSX中,我們創建了名稱、大小(作為選擇)和配料(作為複選框)的輸入。
  3. 每個輸入的值(或複選框的勾選狀態)由order狀態控制。

控制表單的力量

有了這種設置,你可以完全控制你的表單數據。想要添加驗證?很容易!只需修改handleChange函數。需要在提交前轉換數據?只需更新handleSubmit函數。可能性無限!

Controlled Components的常用方法

讓我們總結一些Controlled Components常用的方法:

方法 描述
useState 管理組件狀態的Hook
onChange 輸入更改的事件處理器
onSubmit 表單提交的事件處理器
preventDefault 阻止默認表單提交行為
event.target.value 检索輸入的當前值
event.target.checked 检索複選框的勾選狀態

結論

恭喜你!你剛剛學會了React中的Controlled Components。我們已經覆蓋了單個輸入、複雜表單,甚至創建了一個披薩訂單表單(想到這裡我就餓了!)。

記住,Controlled Components讓你可以精確地管理表單數據。起初可能看起來工作量很大,但你所獲得的控制和靈活性是值得的。

在你繼續React之旅的時候,你會發現無數使用Controlled Components的方法。也許你會創建一個博客文章編輯器,一個用戶註冊表單,或者甚至是披薩配送應用(如果你真的這麼做了,請給我一個優惠券代碼!)。

持續練習,保持好奇心,並且快樂編程!

Credits: Image by storyset