Step-by-Step V1 Example
(Details about this example are on the overview page)
Steps:1234567891011121314
Step 13
- Last step
- Let's start with `filter.toLowerCase()`. It does the same that as the previous step where it lowercases a string. (In this case, it's the text coming in from the filter instead of the invoice name.)
- That lower cased value is compared against the first part of the invoice name via `.startsWith`.
- The return value isn't directly visible, but if the values match, a `true` gets returned and the invoice shows up in the final output
- If the values do not match, the return value is `false` and that particiual invoice gets removed from the output by the filter.
- By using `.startsWith` if the first letters we type in the input search box match the first letters of the name of the invoice we get true. And becasue we added .toLowerCase() to both the `name` and the `filter` the case doesn't matter
File: routes/invoices.jsx
1import {2 NavLink,3 Outlet,4 useSearchParams,5} from "react-router-dom";6import { getInvoices } from "../data";78export default function Invoices() {9 let invoices = getInvoices();10 let [searchParams, setSearchParams] = useSearchParams();1112 return (13 <div style={{ display: "flex" }}>14 <nav15 style={{16 borderRight: "solid 1px",17 padding: "1rem",18 }}19 >20 <input21 value={searchParams.get("filter") || ""}22 onChange={(event) => {23 let filter = event.target.value;24 if (filter) {25 setSearchParams({ filter });26 } else {27 setSearchParams({});28 }29 }}30 />31 {invoices32 .filter((invoice) => {33 let filter = searchParams.get("filter");34 if (!filter) return true;35 let name = invoice.name.toLowerCase();36 return name.startsWith(filter.toLowerCase());37 })38 .map((invoice) => (39 <NavLink40 style={({ isActive }) => ({41 display: "block",42 margin: "1rem 0",43 color: isActive ? "red" : "",44 })}45 to={`/invoices/${invoice.number}`}46 key={invoice.number}47 >48 {invoice.name}49 </NavLink>50 ))}51 </nav>52 <Outlet />53 </div>54 );55}