Open History to see the last commit
1# React-Location
2β
3<a href="https://npmjs.com/package/react-location" target="\_parent">
4 <img alt="" src="https://img.shields.io/npm/dm/react-location.svg" />
5</a>
6<a href="https://spectrum.chat/react-location" target="\_parent">
7 <img alt="" src="https://img.shields.io/badge/spectrum-react--chat-purple.svg" />
8</a>
9<a href="https://github.com/tannerlinsley/react-location" target="\_parent">
10 <img alt="" src="https://img.shields.io/github/stars/tannerlinsley/react-location.svg?style=social&label=Star" />
11</a>
12<a href="https://twitter.com/tannerlinsley" target="\_parent">
13 <img alt="" src="https://img.shields.io/twitter/follow/tannerlinsley.svg?style=social&label=Follow" />
14</a>
15β
16### βοΈ React-Location is a modern Router and location API for React
17β
18It's been built with the following considerations in mind:
19β
20- Clean and clear routing syntax
21- Familiar API for productivity
22- Functional query params & URL parsing
23- Complex Link generation
24- Relative Routing + Links
25- Both Colocated or Nested Route structure
26- Programmatic Navigation
27- Hooks
28- Support for URL or in-memory location sources
29β
30## Get Started
31β
321. Install `react-location`
33β
34```sh
35npm install react-location --save
36# or
37yarn add react-location
38```
39β
402. Import and use `react-location`
41β
42```js
43import { React } from 'react'
44import { render } from 'react-dom'
45import { LocationProvider, Match, MatchFirst, Link } from 'react-location'
46β
47render(
48 <LocationProvider>
49 <nav>
50 <Link to="/">Home</Link>
51 <Link to="dashboard">Dashboard</Link>
52 <Link to="invoices">Invoices</Link>
53 </nav>
54 <div>
55 <Match path="/">
56 <div>This is Home</div>
57 </Match>
58 <Match path="dashboard">
59 <div>This is the Dashboard</div>
60 </Match>
61 <Match path="invoices">
62 <MatchFirst>
63 <Match path="/">
64 <div>Invoices</div>
65 <ul>
66 <li>
67 <Link to="new">New Invoice</Link>
68 </li>
69 <li>
70 <Link to="1">Invoice 1</Link>
71 </li>
72 <li>
73 <Link to="2">Invoice 2</Link>
74 </li>
75 <li>
76 <Link to="3">Invoice 3</Link>
77 </li>
78 </ul>
79 </Match>
80 <Match path="new">
81 <Link to="..">Back</Link>
82 <div>This is a new invoice!</div>
83 </Match>
84 <Match path=":invoiceID">
85 {({ params }) => (
86 <div>
87 <Link to="..">Back</Link>
88 This is invoice #{params.invoiceID}
89 </div>
90 )}
91 </Match>
92 </MatchFirst>
93 </Match>
94 </div>
95 </LocationProvider>,
96)
97```
98β
99# Table of Contents
100β
101- [Documentation](#documentation)
102 - [LocationProvider](#locationprovider)
103 - [Match](#match)
104 - [MatchFirst](#matchfirst)
105 - [Link](#link)
106 - [useLocation, Location, withLocation](#uselocation-location-withlocation)
107 - [Redirect](#redirect)
108 - [createHistory](#createhistory)
109 - [createMemorySource](#creatememorysource)
110 - [Location API](#location-api)
111 - [navigate](#navigate)
112 - [isMatch](#ismatch)
113 - [SSR](#ssr)
114- [Contribution and Roadmap](#contribution-and-roadmap)
115- [Inspiration and Thanks](#inspiration-and-thanks)
116β
117# Documentation
118β
119## LocationProvider
120β
121**Required: true**
122β
123The `LocationProvider` component is the root Provider component for `react-location` in your app. Render it at least once in the highest sensible location within your application. You can also use this component to preserve multiple location instances in the react tree at the same, which is useful for things like route animations or location mocking.
124β
125| Prop | Required | Description |
126| -------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
127| history | false | The history object to be used internally by react-location |
128| basepath | false | The basepath prefix for all URLs (not-supported for memory source histories) |
129| location | false | A custom location to use instead of creating a new one. If a location is passed here, all other props will be ignored and will be inherited from the custom location instead. This useful for things like animation or preserving multiple locations in the tree at the same time. |
130| children | true | The children to pass the location context to |
131β
132**Example: Basic**
133β
134```javascript
135import { LocationProvider } from 'react-location'
136β
137return (
138 <LocationProvider>
139 <div>Your Application</div>
140 </LocationProvider>
141)
142```
143β
144**Example: Memory History**
145β
146```javascript
147import {
148 createMemorySource,
149 createHistory,
150 LocationProvider,
151} from 'react-location'
152β
153const source = createMemorySource('/')
154history = createHistory(source)
155β
156return (
157 <LocationProvider history={history}>
158 <div>...</div>
159 </LocationProvider>
160)
161```
162β
163**Example: Animated Routes**
164β
165```javascript
166import { LocationProvider, Location, Match } from 'react-location'
167β
168const AnimatedWrapper = ({ children }) => (
169 <Location>
170 {location => (
171 // Get the current location and its id
172 // Use location.id as the unique ID in your animations
173 <TransitionGroup className="transition-group">
174 <CSSTransition key={location.id} classNames="fade" timeout={500}>
175 {/* Manually pass LocationProvider the location prop for each animation */}
176 <LocationProvider location={location} />
177 </CSSTransition>
178 </TransitionGroup>
179 )}
180 </Location>
181)
182β
183render(
184 <LocationProvider>
185 <AnimatedWrapper>
186 <MatchFirst>
187 <Match path="/page/:pageID">
188 {({ pageID, location }) => (
189 <div
190 className="page"
191 style={{ background: `hsl(${pageID * 75}, 60%, 60%)` }}
192 >
193 {pageID}
194 </div>
195 )}
196 </Match>
197 </MatchFirst>
198 </AnimatedWrapper>
199 </LocationProvider>,
200)
201```
202β
203## Match
204β
205The `Match` component is used to render content when its path matches the current history's location. It is generally used for routing purposes. It also provides the new relative matching path to child `Match` components, allowing for clean nested route definition.
206β
207| Prop | Required | Description |
208| ---------------------------------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
209| path | true | The path to match (relative to the nearest parent `Match` component or root basepath) |
210| children | | The content to be rendered when the path matches the current location |
211| children(params, location) | | The function to be called when the path matches the current location. This function is called with any route params available in context and the [location API](#location-api) |
212| render(params, location) | | The function to be called when the path matches the current location. This function is called with any route params available in context and the [location API](#location-api) |
213| <component {...params} location /> | | The component to be rendered when the path matches the current location. This component is renderd with any route params available in context **as props** and the [location API](#location-api) as the `location` prop |
214β
215**Example**
216β
217```javascript
218// Render children directly
219render(<Match path="about">About me</Match>)
220β
221// Use children as a function
222render(
223 <Match path=":invoiceID">
224 {({ invoiceID }) => <div>This is invoice #{invoiceID}</div>}
225 </Match>,
226)
227β
228// Use a render function
229render(
230 <Match
231 path=":invoiceID"
232 render={({ invoiceID }) => <div>This is invoice #{invoiceID}</div>}
233 />,
234)
235β
236// Use a component
237const Invoice = ({ invoiceID, location, dark }) => (
238 <div classname={dark && 'dark'}>This is invoice #{invoiceID}</div>
239)
240β
241render(<Match path=":invoiceID" component={Invoice} dark />)
242```
243β
244## MatchFirst
245β
246The `MatchFirst` component is used to selectively render the first child component that is av valid match and/or provide fallbacks. This is useful for:
247β
248- Nesting and Relative Routes
249- Matching index routes and hard-coded routes before dynamic ones
250- Default / fallback routes
251β
252**Example - Route Params**
253β
254```javascript
255render(
256 <Match path="invoices">
257 <MatchFirst>
258 <Match path="/">This route would match and display at `/invoices/`</Match>
259 <Match path="new">
260 This route would match and display at `/invoices/new`
261 </Match>
262 <Match path=":invoiceID">
263 {({ params }) => (
264 <div>
265 This route would match for all other `/invoices/:invoiceID/` routes
266 </div>
267 )}
268 </Match>
269 </MatchFirst>
270 </Match>,
271)
272```
273β
274**Example - Default / Fallback Route**
275β
276```javascript
277render(
278 <MatchFirst>
279 <Match path="/">This route would match and display at `/`</Match>
280 <Match path="about">This route would match and display at `/about`</Match>
281 <div>
282 This element would be rendered as the fallback when no Matches are found
283 </div>
284 </MatchFirst>,
285)
286```
287β
288## Link
289β
290The `Link` component allows you to generate `<a href/>` links for navigation, capable of updating the:
291β
292- Route path + hash
293- Query parameters
294- State
295- Push vs. Replace
296β
297The links generated by it are designed to work perfectly with `Open in new Tab` + `ctrl + left-click` and `Open in new window...`. They are also capable of receiving "active" props (depending on the `activeType` passed) to decorate the link when the link is currently active relative to the current location.
298β
299| Prop | Type | Description |
300| ------------------------ | --------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
301| ...[navigate](#navigate) | | All properties for the [navigate](#navigate) method are supported here. |
302| activeType | string (one of `partial`, `path`, `hash` or `full`) | Defaults to `full`. Defines which matching strategy is used to determine if the link is `active` or not. See the table below for more information. |
303| getActiveProps | function | A function that is passed the [Location API](#location-api) and returns additional props for the `active` state of this link. These props override other props passed to the link (`style`'s are merged, `className`'s are concatenated) |
304β
305**Example: The basics**
306β
307```javascript
308render(
309 <div>
310 <Link to="/home">I will navigate to `/home`</Link>
311 <Link to="todos">
312 I will navigate to `./todos`, relative to the current location
313 </Link>
314 <Link to="..">I will navigate up one level in the location hierarchy.</Link>
315 <Link to="#somehash">
316 I will navigate to the hash `somehash` at the current location
317 </Link>
318 <Link to="/search?stringQuery=yes!">I will navigate to `/search?stringQuery=yes!`</Link>
319 <Link
320 query={
321 someParams: true,
322 otherParams: 'gogogo',
323 object: { nested: { list: [1, 2, 3], hello: "world" } }
324 }}
325 >
326 I will navigate to the current location + `?someParams=true&otherParams=gogogo&object=%7B%22nested%22%3A%7B%22list%22%3A%5B1%2C2%2C3%5D%2C%22hello%22%3A%22world%22%7D%7D`
327 </Link>
328 <Link
329 query={query => ({
330 ...query,
331 addThis: 'This is new!',
332 removeThis: undefined
333 })}
334 >
335 I will add `addThis='This is new!' and also remove the `removeThis` param to/from the query params on the current page
336 </Link>
337 </div>
338);
339```
340β
341**Example: Using `getActiveProps`**
342β
343The following link will be green with `/about` as the current location.
344β
345```javascript
346<Link
347 to="/about"
348 getActiveProps={location => ({
349 style: { color: 'green' },
350 })}
351>
352 About
353</Link>
354```
355β
356**Using `activeType`**
357β
358As mentioned above, `activeType` configures when a link is considered "active", and when `getActiveProps()` is run and applied to the link. Below is a table demonstrating the various options and how they behave:
359β
360| Type | Description | Example |
361| --------- | -------------------------------------------------------- | ------- |
362| `full` | Match agains the fully href including the query and hash | |
363| `hash` | | |
364| `path` | | |
365| `partial` | | |
366β
367let isCurrent;
368if (activeType === "partial") {
369isCurrent = startsWith(href, linkHrefWithQuery);
370} else if (activeType === "path") {
371isCurrent = pathname === linkHref;
372} else if (activeType === "hash") {
373isCurrent = pathname === linkHrefWithHash;
374} else {
375isCurrent = href === linkHrefWithQuery;
376}
377β
378## useLocation, Location, withLocation
379β
380The `useLocation` hook, `Location` component and `withLocation` HOC all return the current [location API](#location-api) from context when used.
381β
382**Example**
383β
384```javascript
385import { useLocation, Location, withLocation } from "react-location";
386β
387// Hook
388export function MyComponent() {
389 const location = useLocation();
390 // use location...
391}
392β
393// Component
394export function MyComponent() {
395 return (
396 <Location>
397 {location => {
398 // use location...
399 }}
400 </Location>
401 )
402}
403β
404// HOC
405export const MyComponent = withLocation(({ location }) => {
406 // use location...
407})
408```
409β
410## Redirect
411β
412The `Redirect` component can be used to redirect from one route to another based on a matching path. It can be rendered standalone or within a `MatchFirst` component. If the `from` prop is left undefined, it will always match and always redirect if rendered.
413β
414| Prop | Description |
415| ------------------------ | --------------------------------------------------------------------------------------------------------------- |
416| from | The path to match. Behaves the same way a `Match` does. If not defined, will always redirect when rendered. |
417| ...[navigate](#navigate) | All properties for the [navigate](#navigate) method are supported here, but with `replace` defaulting to `true` |
418β
419## createHistory
420β
421Creates a custom history object. You can pass this history object to the `LocationProvider` or just use it to listen to the history of the page.
422β
423**Example**
424β
425```javascript
426import { createMemorySource, createHistory } from 'react-location'
427β
428// Use the window history (DOM only)
429let history = createHistory(window)
430β
431// You can also pass it a memorySource instance for in-memory or SSR routing
432let source = createMemorySource('/starting/url')
433let history = createHistory(source)
434```
435β
436## createMemorySource
437β
438Creates a source for `createHistory` that manages a history stack in memory. You may want to use a memory source if you are using an environment that doesn't support or have reliable access to the window location eg. Node, Electron, Ionic, Cordova etc.
439β
440See [createHistory](#createHistory) for an example
441β
442# Location API
443β
444React-Location's model and API is located in a single object, passed via context, throughout the library. It contains both the current state and API for location. It is made available via:
445β
446- The return result for the `useLocation` hook, `Location` component, `withLocation` HOC. [See Example](#uselocation-location-withlocation)
447- Via props passed to the `render` function, `children` function, and `component`s that are rendered with the `Match` component. [See Example](#match)
448- The first parameter of the `Link` component's `getActiveProps` prop function. [See Example](#link)
449β
450The following **properties** are available on the location API:
451β
452| Property | Type | Description |
453| ---------- | ------ | ------------------------------------------------------------ |
454| `basepath` | string | The basepath of the API, including parent paths. |
455| `pathname` | string | The pathname of the location. |
456| `hash` | string | The hash of the location with the `#` removed. |
457| `params` | object | The params, deserialized to an `object` with key-value pairs |
458| `query` | object | The query, deserialized to an `object` with key-value pairs |
459| `search` | string | The search string of the location |
460| `state` | object | The location's custom state `object` |
461| `href` | string | The full url |
462| `id` | string | The unique id for the current stack in history |
463| `history` | object | The underlying `history` object used to power the location |
464β
465The following **methods** are available on the location API:
466β
467### `navigate`
468β
469The `navigate` function allows you to programmatically navigate your application. It is the same method that powers all of the components in this library.
470β
471**Usage**
472β
473```javascript
474const Promise = navigate(
475 to:string,
476 {
477 query: object{} | function(old) => new,
478 state: object{} | function(old) => new,
479 replace: boolean = false
480 preview: boolean = false
481 }
482);
483```
484β
485### `isMatch`
486β
487The `isMatch` function allows you to programmatically test a path for a match **within the closest relative route**.
488β
489**Usage**
490β
491```javascript
492const MyComponent = () => {
493 const { isMatch } = useLocation()
494β
495 isMatch('about') // false
496 isMatch('me') // true
497}
498β
499const App = () => {
500 // path === '/about/me'
501 ;<Match path="about">
502 <MyComponent />
503 </Match>
504}
505```
506β
507**Argument Information**
508β
509| Prop | Type | Description |
510| ------- | --------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- |
511| to | string | The path this link navigates to. It can be absolute, relative, external and can also contain a #hash. Defaults to the current location if not defined |
512| query | object/function | Either (1) the replacement query parameters for this link as an object, or (2) a function that receives the old query parameters and returns new ones |
513| state | object/function | Either (1) the replacement state for this link as an object, or (2) a function that receives the old state and returns new ones |
514| replace | boolean | Whether or not to replace the current history entry when this link is clicked |
515| preview | boolean | When `true`, returns the `href` produced by this Link |
516β
517# SSR
518β
519Server-side rendering is easy with react-location. You can use `createMemorySource`, `createHistory` and `LocationProvider` to mock your app into a specific state for SSR:
520β
521```js
522import {
523 createMemorySource,
524 createHistory,
525 LocationProvider,
526} from 'react-location'
527β
528let history
529if (typeof document !== 'undefined') {
530 history = createHistory(window)
531} else {
532 const source = createMemorySource('/blog/post/2')
533 history = createHistory(source)
534}
535β
536return (
537 <LocationProvider history={history}>
538 <div>...</div>
539 </LocationProvider>
540)
541```
542β
543Looking to do static site generation? You should try react-location with [React Static!](https://react-static.js.org)
544β
545## Contribution and Roadmap
546β
547- [ ] Improve Accessibility (Hopefully to the level of Reach Router)
548- [ ] Write Tests
549- [ ] Continuous Integration & Automated Releases
550β
551Open an issue or PR to discuss!
552β
553## Inspiration and Thanks
554β
555This library was heavily inspired by both [`@reach/router`](https://reach.tech/router) and [`react-router`](https://reacttraining.com/react-router/). In some cases, utility functions were copy and pasted into this library (that's how good they are). Both are extremely fantastic tools that have set standards for the quality of routers in React.]