New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

Replace react-router with @reach/router #6918

Merged
merged 27 commits into from Aug 6, 2018
Commits
Jump to file or symbol
Failed to load files and symbols.
+721 鈭507
Diff settings

Always

Just for now

@@ -41,7 +41,7 @@ exports.onCreatePage = async ({ page, actions }) => {
// page.matchPath is a special key that's used for matching pages
// only on the client.
if (page.path.match(/^\/app/)) {
page.matchPath = "/app/:path"
page.matchPath = "/app/*"
// Update the page.
createPage(page)
Copy path View file
@@ -0,0 +1,131 @@
---
title: Gatsby Link
---
A `<Link>` component for Gatsby.
It's a wrapper around
[@reach/router's Link component](https://reach.tech/router/api/Link)
that adds enhancements specific to Gatsby. All props are passed through to @reach/router's `Link` component.
You can set the `activeStyle` or `activeClassName` prop to add styling
attributes to the rendered element when it matches the current URL.
Gatsby does per-route code splitting. This means that when navigating to a new
page, the code chunks necessary for that page might not be loaded. This is bad as
any unnecessary latency when changing pages should be avoided. So to avoid that,
Gatsby preloads code chunks and page data.
Preloading is triggered by a link entering the viewport; Gatsby uses
`Link`'s `innerRef` property to create a new InteractionObserver (on
supported browsers) to monitor visible links. This way, Gatsby only prefetches
code/data chunks for pages the user is likely to navigate to. You can also get
access to the link element by passing in a `innerRef` prop.
## How to use
In JavaScript:
```jsx
import React from "react"
import { Link } from "gatsby"
class Page extends React.Component {
render() {
return (
<div>
<Link
to="/another-page/"
activeStyle={{
color: "red",
}}
innerRef={el => {
this.myLink = el
}}
>
Another page
</Link>
</div>
)
}
}
```
## Programmatic navigation
For cases when you can only use event handlers for navigation, you can use `push` or `replace`. `push` is a wrapper for `history.push` and `replace` wraps `history.replace`.
```jsx
import { push } from "gatsby"
render () {
<div onClick={ () => push('/example')}>
<p>Example</p>
</div>
}
```
Note that `push` was previously named `navigateTo`. `navigateTo` is deprecated in Gatsby v2.
## Prefixed paths helper
It is common to host sites in a sub-directory of a site. Gatsby let's you [set
the path prefix for your site](/docs/path-prefix/). After doing so, Gatsby's `<Link>` component will automatically handle constructing the correct URL in development and production.
For pathnames you construct manually, there's a helper function, `withPrefix` that prepends your path prefix in production (but doesn't during development where paths don't need prefixed).
```jsx
import { withPrefix } from "gatsby"
const IndexLayout = ({ children, location }) => {
const isHomepage = location.pathname === withPrefix("/")
return (
<div>
<h1>Welcome {isHomepage ? "home" : "aboard"}!</h1>
{children}
</div>
)
}
```
## Use `<Link>` only for internal links!
This component is intended _only_ for links to pages handled by Gatsby. For links to pages on other domains or pages on the same domain not handled by the current Gatsby site, use the normal `<a>` element.
Sometimes you won't know ahead of time whether a link will be internal or not,
such as when the data is coming from a CMS.
In these cases you may find it useful to make a component which inspects the
link and renders either with Gatsby's `<Link>` or with a regular `<a>` tag
accordingly.
Since deciding whether a link is internal or not depends on the site in
question, you may need to customize the heuristic to your environment, but the
following may be a good starting point:
```jsx
import { Link as GatsbyLink } from "gatsby"
const Link = ({ children, to, ...other }) => {
// Tailor the following test to your environment.
// This example assumes that any internal link (intended for Gatsby)
// will start with exactly one slash, and that anything else is external.
const internal = /^\/(?!\/)/.test(to)
// Use Gatsby Link for internal links, and <a> for others
if (internal) {
return (
<GatsbyLink to={to} {...other}>
{children}
</GatsbyLink>
)
}
return (
<a href={to} {...other}>
{children}
</a>
)
}
export default Link
```
@@ -25,6 +25,9 @@ This is a reference for upgrading your site from Gatsby v1 to Gatsby v2. While t
- [Convert to either pure CommonJS or pure ES6](#convert-to-either-pure-commonjs-or-pure-es6)
- [Move Babel configuration](#move-babel-configuration)
- [Restore v1 PostCSS plugin setup](#restore-v1-post-css-setup)
- [Migrate from React Router` to @reach/router](#migrate-from-react-router-to-reachrouter)
- [APIs onPreRouteUpdate and onRouteUpdate no longer called with the route update action](#apis-onprerouteupdate-and-onrouteupdate-no-longer-called-with-the-route-update-action)
- [Browser API `relaceRouterComponent` was removed](#browser-api-relaceroutercomponent-was-removed)
- [Don't query nodes by ID](#dont-query-nodes-by-id)
- [Typography.js Plugin Config](#typographyjs-plugin-config-changes)
@@ -349,6 +352,197 @@ module.exports = () => ({
})
```
### Migrate from React Router to @reach/router
We switched our router from [React Router v4](https://reacttraining.com/react-router/) to [@reach/router](https://reach.tech/router) as @reach/router is smaller and most importantly, has 1st class support
for accessibility.
@reach/router is written by [Ryan Florence](https://twitter.com/ryanflorence), who was also the founder of React Router. He says @reach/router restores
things he misses from React Router v3 while retaining the best parts of React Router v4 _and_ adds full accessibility support.
For _most_ sites, this change won't cause any breaking changes as the two routers are quite similar.
Two common ways this change _might_ break your site is:
- You use the object form of the `to` prop in the `<Link>` component
- You have client side routes
Read more about the features of our new router at https://reach.tech/router
**NOTE:** One prominant feature of @reach/router, relative routes, isn't working currently in Gatsby. We're working with Ryan Florence
on fixing that so hopefully it'll be supported soon.
Read on for instructions on migrating your site to @reach/router.
#### Only string `to` allowed
React Router allowed you to pass objects to the `to` prop e.g.
```jsx
<Link
to={{ pathname: `/about/`, search: `fun=true&pizza=false`, hash: `people` }}
>
Our people
</Link>
```
React Router would then simply concatenate the object values together into the full pathname e.g. `/about/?fun=true&pizza=false#people`.
Now you'll need to concatenate together the full pathname yourself.
```diff
- <Link to={{ pathname: `/about/`, search: `fun=true&pizza=false`, hash: `people`}}>Our people</Link>
+ <Link to={`/about/?fun=true&pizza=false#people`}>Our people</Link>
```
#### Pass state to the `state` prop
Previously with React Router to pass state to a link, you would pass it as part of a `to` object prop.
Now, to add state to a link, pass it via a `state` prop.
```jsx
const NewsFeed = () => (
<div>
<Link to="photos/123" state={{ fromNewsFeed: true }} />
</div>
)
const Photo = ({ location, photoId }) => {
if (location.state.fromFeed) {
return <FromFeedPhoto id={photoId} />
} else {
return <Photo id={photoId} />
}
}
```
#### A `history` prop is no longer passed to page components
React Router would pass a `history` prop to components that you could use to navigate.
If you need to do programmatic navigation, import instead the @reach/router's `navigate` function.
```javascript
import { navigate } from "@reach/router"
```
#### The following props are no longer available on `<Link>`
- `exact`
- `strict`
- `location`
`exact` and `strict` are no longer necessary as @reach/router does matching
this way by default.
You could pass `location` previously to manually compute whether the
link is active or not. For advanced link stylings, use `getProps` now.
#### Use `getProps` for advanced link styling
Gatsby's `<Link>` component supports out-of-the-box `activeClassName` and `activeStyle`.
If you have more advanced styling needs, [use the `getProps` prop](https://reach.tech/router/api/Link).
#### Change client paths to use a splat
When creating a client route in `gatsby-node.js`, use a `*` to select all child routes instead of `:path`.
```diff
exports.onCreatePage = async ({ page, actions }) => {
const { createPage } = actions
// page.matchPath is a special key that's used for matching pages
// only on the client.
if (page.path.match(/^\/app/)) {
- page.matchPath = "/app/:path"
+ page.matchPath = "/app/*"
// Update the page.
createPage(page)
}
}
```
#### Migrating React Router client routes to @reach/router
- Use `<Location>` instead of `withRouter`
- import `{ navigate }` from `@reach/router` for programmatic navigation instead of the history object
- There's no `Route` component any more. You add a `<Router>` component (a site can have as many routers as it wishes) and then the immediate children of `<Router>` must have a prop named `path`.
A basic example of the `<Router>` component:
```jsx
import React from "react"
import { Router } from "@reach/router"
export default () => (
<Router>
<div path="/">I am the home!</div>
<div path="/about">Here's a bit about me</div>
<div path="/store">Buy my t-shirts!</div>
</Router>
)
```
Here's a more complex example of migrating a `<PrivateRoute>` component (used
in store.gatsbyjs.org) from React Router to @reach/router.
```diff
import React from 'react';
-import { Redirect, Route } from 'react-router-dom';
+import { Router, navigate } from '@reach/router';
import { isAuthenticated } from '../../utils/auth';
-export default ({ component: Component, ...rest }) => (
- <Route
- {...rest}
- render={props =>
- !isAuthenticated() ? (
- // If we鈥檙e not logged in, redirect to the home page.
- <Redirect to={{ pathname: '/login' }} />
- ) : (
- <Component {...props} />
- )
- }
- />
-);
+export default ({ component: Component, ...rest }) => {
+ if (!isAuthenticated() && window.location.pathname !== `/login`) {
+ // If we鈥檙e not logged in, redirect to the home page.
+ navigate(`/app/login`);
+ return null;
+ }
+
+ return (
+ <Router>
+ <Component {...rest} />
+ </Router>
+ );
+};
```
Here's links to diffs for three sites with client routes that were upgraded to @reach/router
- [store.gatsbyjs.org](https://github.com/gatsbyjs/store.gatsbyjs.org/pull/111)
- [client-only-routes](https://github.com/gatsbyjs/gatsby/pull/6918/files#diff-69757e54875e28ef83eb8efe45a33fdf)
- [simple-auth](https://github.com/gatsbyjs/gatsby/pull/6918/files#diff-53ac112a4b2ec760b26a86c953df2339)
### APIs `onPreRouteUpdate` and `onRouteUpdate` no longer called with the route update action
React Router v4 would tell us the "action" (push/replace) that triggered the route
transition. We passed this as one of the arguments along with `location` to plugins. @reach/router doesn't support this so we've removed it from the API calls.
### Browser API `relaceRouterComponent` was removed
React Router allowed you to swap out its history object. To enable this in Gatsby, an API, `replaceRouterComponent` was added so that you could use a custom version of history or React Router. As @reach/router doesn't support this, we've removed this API.
We did, erroneously, suggest using this API for adding support for Redux, etc. where you need to wrap the root Gatsby component with your own component.
If you were using `replaceRouterComponent` for this, you'll need to migrate to
`wrapRootComponent`. See this PR migrating the `using-redux` example site as a pattern to follow https://github.com/gatsbyjs/gatsby/pull/6986
### Don't query nodes by ID
Source and transformer plugins now use UUIDs for IDs. If you used glob or regex to query nodes by id then you'll need to query something else.
@@ -47,7 +47,7 @@ Open the file at `/src/pages/index.js`. The code in this file creates a componen
> 馃挕 Gatsby uses **hot reloading** to speed up your development process. Essentially, when you鈥檙e running a Gatsby development server, the Gatsby site files are being 鈥渨atched鈥 in the background 鈥 any time you save a file, your changes will be immediately reflected in the browser. You don鈥檛 need to hard refresh the page, or restart the development server 鈥 your changes just appear.
2. Let鈥檚 make our changes a little more visible. Try replacing the code in `/src/pages/index.js` with the code below, and save again. You鈥檒l see changes to the text; The text color will be purple, and the font size will be larger.
2. Let鈥檚 make our changes a little more visible. Try replacing the code in `/src/pages/index.js` with the code below, and save again. You鈥檒l see changes to the text; The text color will be purple, and the font size will be larger.
```jsx
import React from "react"
@@ -1,17 +1,11 @@
const Promise = require(`bluebird`)
const path = require(`path`)
// Implement the Gatsby API 鈥渙nCreatePage鈥. This is
// called after every page is created.
exports.onCreatePage = ({ page, actions }) => {
const { createPage } = actions
return new Promise((resolve, reject) => {
// Make the front page match everything client side.
// Normally your paths should be a bit more judicious.
if (page.path === `/`) {
page.matchPath = `/:path`
createPage(page)
}
resolve()
})
// Make the front page match everything client side.
// Normally your paths should be a bit more judicious.
if (page.path === `/`) {
page.matchPath = `/*`
createPage(page)
}
}
Oops, something went wrong.
ProTip! Use n and p to navigate between commits in a pull request.