Array in State
import React, { useState } from "react";
const options = ["Bell Pepper", "Sausage", "Pepperoni", "Pineapple"];
export default function PersonalPizza() {
const [selected, setSelected] = useState([]);
const toggleTopping = ({target}) => {
const clickedTopping = target.value;
setSelected((prev) => {
if (prev.includes(clickedTopping)) {
return prev.filter(t => t !== clickedTopping);
} else {
return [clickedTopping, ...prev];
}
});
};
return (
<div>
{options.map(option => (
<button value={option} onClick={toggleTopping} key={option}>
{selected.includes(option) ? "Remove " : "Add "}
{option}
</button>
))}
<p>Order a {selected.join(", ")} pizza</p>
</div>
);
}
예제 - Grocery Cart
- item 클릭 시 cart에 담기고, 담긴 item 클릭시 삭제
import React, { useState } from "react";
import ItemList from "./ItemList";
import { produce, pantryItems } from "./storeItems";
export default function GroceryCart() {
const [cart, setCart] = useState([]);
const addItem = (item) => {
setCart((prev) => {
return [item, ...prev]
})
};
const removeItem = (targetIndex) => {
setCart((prev) => {
return prev.filter((item, index) => index !== targetIndex)
})
};
return (
<div>
<h1>Grocery Cart</h1>
<ul>
{cart.map((item, index) => (
<li onClick={() => removeItem(index)} key={index}>
{item}
</li>
))}
</ul>
<h2>Produce</h2>
<ItemList items={produce} onItemClick={addItem} />
<h2>Pantry Items</h2>
<ItemList items={pantryItems} onItemClick={addItem} />
</div>
);
}
Object in State
export default function Login() {
const [formState, setFormState] = useState({});
const handleChange = ({ target }) => {
const { name, value } = target;
setFormState((prev) => ({
...prev,
[name]: value
}));
};
return (
<form>
<input
value={formState.firstName}
onChange={handleChange}
name="firstName"
type="text"
/>
<input
value={formState.password}
onChange={handleChange}
type="password"
name="password"
/>
</form>
);
}
예제 - Edit Profile
import React, { useState } from "react";
export default function EditProfile() {
const [profile, setProfile] = useState({});
const handleChange = ({ target }) => {
const {name, value} = target;
setProfile((prev) => ({
...prev,
[name]: value
}));
};
const handleSubmit = (event) => {
event.preventDefault();
alert(JSON.stringify(profile, '', 2));
};
return (
<form onSubmit={handleSubmit}>
<input
value={profile.firstName || ''}
name="firstName"
type="text"
placeholder="First Name"
onChange={handleChange}
/>
<input
value={profile.lastName || ''}
type="text"
name="lastName"
placeholder="Last Name"
onChange={handleChange}
/>
<input
value={profile.bday || ''}
type="date"
name="bday"
onChange={handleChange}
/>
<input
value={profile.password || ''}
type="password"
name="password"
placeholder="Password"
onChange={handleChange}
/>
<button type="submit">Submit</button>
</form>
);
}