Step-by-Step V1 Example
(Details about this example are on the overview page)
Steps:1234567891011121314
Step 8
- There's a few lines to this chage that include both and `if` and the correspoding `else`
- This is where we can start typeing into the text box again
- We look to see if there is a value in the `filter` variable. If there is, we call `setSearchParams` with the value.
- When `setSearchParams` makes the update it changes the URL address
- The change in the address cascades down into the text box via the `searchParams.get("filter")` call we setup in step 5
- If there is no value, things get emptied out by calling `setSearchParams()` with an empty object (i.e. `{}`)
- So, we can type stuff and update the URL with the search parameter (which will let us bookmark searches), but nothing is happing with the list. We start to handle that next
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 .map((invoice) => (33 <NavLink34 style={({ isActive }) => ({35 display: "block",36 margin: "1rem 0",37 color: isActive ? "red" : "",38 })}39 to={`/invoices/${invoice.number}`}40 key={invoice.number}41 >42 {invoice.name}43 </NavLink>44 ))}45 </nav>46 <Outlet />47 </div>48 );49}