AI Hints
Home›React Tutorial›UI Patterns
React · Lesson 64 of 120

Sorting and Tabs

More UI state.

⏱ 2 min read▶ Video at 53:01🎓 Free
Watch this lesson in the React courseWatch on YouTube ↗Full React course

Tabs and sorting are just more UI state. A string for the active tab, and a string for the sort order. Everything else is derived.

  • More UI state
  • Active tab
  • Sort order

Tabs and sorting

The active tab is just a string in state. Each tab button sets it, and the active one is brighter. Sorting copies the array first, because sort changes an array in place. We sort by name. Run it.

App.jsxjsx
import { useState } from "react";
const PRODUCTS = [{ name: "Trail 500", price: 849.5 }, { name: "Volt 7", price: 2199 }, { name: "City 200", price: 450 }];
const TABS = ["Products", "Reviews", "Delivery"];
export default function App() {
  const [tab, setTab] = useState("Products");
  const [sort, setSort] = useState("price");
  const sorted = [...PRODUCTS].sort((a, b) => sort === "price" ? a.price - b.price : a.name.localeCompare(b.name));
  return (<div>
    {TABS.map(t => <button key={t} onClick={() => setTab(t)} style={{ opacity: t === tab ? 1 : 0.5 }}>{t}</button>)}
    {tab === "Products" && <div className="box">
      <button id="byName" onClick={() => setSort("name")}>Sort by name</button>
      <ol>{sorted.map(p => <li key={p.name}>{p.name} — £{p.price}</li>)}</ol>
    </div>}
    {tab === "Reviews" && <p className="box">4.8 stars from 212 riders.</p>}
    {tab === "Delivery" && <p className="box">Free delivery on orders over £500.</p>}
  </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": "#byName"}]

Summary

Tabs and sorting are small pieces of state, with everything else derived. Next, practice with a product browser.

Key takeaways
  • tab
  • sort
  • [...arr].sort()
Next up: Practice: A Product Browser — lists together