| 1 | ---
|
| 2 | title: URL Values
|
| 3 | ---
|
| 4 |
|
| 5 | # URL Values
|
| 6 |
|
| 7 | [MODES: declarative]
|
| 8 |
|
| 9 | ## Route Params
|
| 10 |
|
| 11 | Route params are the parsed values from a dynamic segment.
|
| 12 |
|
| 13 | ```tsx
|
| 14 | <Route path="/concerts/:city" element={<City />} />
|
| 15 | ```
|
| 16 |
|
| 17 | In this case, `:city` is the dynamic segment. The parsed value for that city will be available from `useParams`
|
| 18 |
|
| 19 | ```tsx
|
| 20 | import { useParams } from "react-router";
|
| 21 |
|
| 22 | function City() {
|
| 23 | let { city } = useParams();
|
| 24 | let data = useFakeDataLibrary(`/api/v2/cities/${city}`);
|
| 25 | // ...
|
| 26 | }
|
| 27 | ```
|
| 28 |
|
| 29 | ## URL Search Params
|
| 30 |
|
| 31 | Search params are the values after a `?` in the URL. They are accessible from `useSearchParams`, which returns an instance of [`URLSearchParams`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams)
|
| 32 |
|
| 33 | ```tsx
|
| 34 | function SearchResults() {
|
| 35 | let [searchParams] = useSearchParams();
|
| 36 | return (
|
| 37 | <div>
|
| 38 | <p>
|
| 39 | You searched for <i>{searchParams.get("q")}</i>
|
| 40 | </p>
|
| 41 | <FakeSearchResults />
|
| 42 | </div>
|
| 43 | );
|
| 44 | }
|
| 45 | ```
|
| 46 |
|
| 47 | ## Location Object
|
| 48 |
|
| 49 | React Router creates a custom `location` object with some useful information on it accessible with `useLocation`.
|
| 50 |
|
| 51 | ```tsx
|
| 52 | function useAnalytics() {
|
| 53 | let location = useLocation();
|
| 54 | useEffect(() => {
|
| 55 | sendFakeAnalytics(location.pathname);
|
| 56 | }, [location]);
|
| 57 | }
|
| 58 |
|
| 59 | function useScrollRestoration() {
|
| 60 | let location = useLocation();
|
| 61 | useEffect(() => {
|
| 62 | fakeRestoreScroll(location.key);
|
| 63 | }, [location]);
|
| 64 | }
|
| 65 | ```
|