React · Lesson 24 of 120
State with Arrays
Add, remove, update.
Arrays in state follow the same rule. Don't push, splice, or sort them in place. Create a new array instead, with spread, filter, or map.
- Same rule
- No push or splice
- New arrays
A wish list
Add uses spread to make a new array, with the new item at the end. Remove uses filter, to keep every item except one. We add a bike, then remove the helmet. Run it.
App.jsxjsx
import { useState } from "react";
export default function App() {
const [items, setItems] = useState(["Helmet", "Lights"]);
const add = () => setItems([...items, "Trail 500"]);
const remove = name => setItems(items.filter(i => i !== name));
return (
<div>
<button id="add" onClick={add}>Add Trail 500</button>
<ul>
{items.map(i => <li key={i}>{i} <button className={`rm-${i[0]}`} onClick={() => remove(i)}>×</button></li>)}
</ul>
</div>
);
}Also uses style.css
body{font-family:-apple-system,Helvetica,Arial,sans-serif;margin:22px;font-size:21px;color:#1d1d1f;background:#fafafa}
h1{font-size:34px;margin:0 0 14px} h2{font-size:26px;margin:0 0 10px}
button{font-size:19px;padding:9px 18px;border-radius:9px;border:0;background:#61dafb;color:#111;font-weight:600;margin:4px 6px 4px 0}
input{font-size:19px;padding:8px 10px;border:2px solid #bbb;border-radius:8px}
li{margin:5px 0} .box{padding:14px;border-radius:12px;background:#fff;border:2px solid #ddd;margin:8px 0}
.done{text-decoration:line-through;color:#999} small{color:crimson;display:block;font-size:16px} .big{font-size:64px;font-weight:800}Also uses actions.json
[{"click": "#add"}, {"click": ".rm-H"}]Array cheat sheet
To add, spread the old array and add the item. To remove, use filter. To change one item, use map, and return a changed copy for that item. To sort, copy first, then sort the copy.
| Task | Use |
|---|---|
| Add | [...items, item] |
| Remove | items.filter(...) |
| Change one | items.map(...) |
| Sort | [...items].sort() |
Summary
Create new arrays with spread, filter, and map, instead of changing them in place. Next, forms.
Key takeaways- [...items, x]
- filter
- map
Next up: Forms — controlled inputs