Step-by-Step V1 Example
(Details about this example are on the overview page)
Steps:1234567891011121314
Step 11
- Now we put in our first return value for the filter.
- This looks at the value for `filter` in the URL via the `filter` variable we just set and if it's `falsy` (including undefined or empty) the line returs true.
- What this means for us is that if the URL doesn't have have a filter this line will return true for every item so they all show up on the page (i.e. http://localhost:3131/invoices).
- However, if there is a filter value in the URL (e.g. http://localhost:3131/invoices?filter=testing), then the line doesn't return true for anything so nothing shows up.
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 })36 .map((invoice) => (37 <NavLink38 style={({ isActive }) => ({39 display: "block",40 margin: "1rem 0",41 color: isActive ? "red" : "",42 })}43 to={`/invoices/${invoice.number}`}44 key={invoice.number}45 >46 {invoice.name}47 </NavLink>48 ))}49 </nav>50 <Outlet />51 </div>52 );53}