Skip to content
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’ll 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
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
af1227c
Get @reach/router working probably in development
KyleAMathews Jul 31, 2018
e0f2bec
Moer stuff working
KyleAMathews Aug 1, 2018
091ce37
Don't support to as an object
KyleAMathews Aug 1, 2018
7a6c868
Add back support for activeClassName & activeStyle
KyleAMathews Aug 1, 2018
48e3733
Fix path for RouteHandlers
KyleAMathews Aug 1, 2018
874acf1
Pull in parse-path util from react-router
KyleAMathews Aug 1, 2018
a31706a
remove console.logs and add TODO
KyleAMathews Aug 2, 2018
596796b
Merge remote-tracking branch 'origin/master' into reach-router
KyleAMathews Aug 2, 2018
9b7e648
Remove now unused webpack rules to trim down react-router
KyleAMathews Aug 2, 2018
fed26d1
Some fixes from merge
KyleAMathews Aug 2, 2018
65e7d86
Fix problems identified in review earlier
KyleAMathews Aug 3, 2018
9db958c
Remove old typescript definitions
KyleAMathews Aug 3, 2018
75ebf29
Merge remote-tracking branch 'origin/master' into reach-router
KyleAMathews Aug 4, 2018
96c1c92
Restore and update the <Link> documentation for v2/@reach/router
KyleAMathews Aug 4, 2018
33583a2
Also set the className when the site is active per @pieh's advice
KyleAMathews Aug 4, 2018
cee482f
Upgrade client-only-paths example site
KyleAMathews Aug 4, 2018
ad0b949
Upgrade simple-auth example site
KyleAMathews Aug 4, 2018
11753c0
Fix lint errors
KyleAMathews Aug 4, 2018
197ed0e
Merge remote-tracking branch 'origin/master' into reach-router
KyleAMathews Aug 6, 2018
7c61690
Migration docs
KyleAMathews Aug 6, 2018
8c0f084
Note that can't use relative routes w/ @reach/router
KyleAMathews Aug 6, 2018
97ff092
Fix/remove tests that are irrelevant now
KyleAMathews Aug 6, 2018
01b9959
Fix imports
KyleAMathews Aug 6, 2018
4c7e80c
Use v2 version of children for layout
KyleAMathews Aug 6, 2018
bc7035c
mini typos
m-allanson Aug 6, 2018
ea00a10
Merge remote-tracking branch 'origin/master' into reach-router
KyleAMathews Aug 6, 2018
06d9c77
Document that history prop no longer passed to page components
KyleAMathews Aug 6, 2018
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/docs/building-apps-with-gatsby.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
131 changes: 131 additions & 0 deletions docs/docs/gatsby-link.md
Original file line number Diff line number Diff line change
@@ -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
```
194 changes: 194 additions & 0 deletions docs/docs/migrating-from-v1-to-v2.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down Expand Up @@ -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’re 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’re 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.
Expand Down
2 changes: 1 addition & 1 deletion docs/tutorial/part-one/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -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’re running a Gatsby development server, the Gatsby site files are being “watched” in the background — any time you save a file, your changes will be immediately reflected in the browser. You don’t need to hard refresh the page, or restart the development server — your changes just appear.

2. Let’s make our changes a little more visible. Try replacing the code in `/src/pages/index.js` with the code below, and save again. You’ll see changes to the text; The text color will be purple, and the font size will be larger.
2. Let’s make our changes a little more visible. Try replacing the code in `/src/pages/index.js` with the code below, and save again. You’ll see changes to the text; The text color will be purple, and the font size will be larger.

```jsx
import React from "react"
Expand Down
18 changes: 6 additions & 12 deletions examples/client-only-paths/gatsby-node.js
Original file line number Diff line number Diff line change
@@ -1,17 +1,11 @@
const Promise = require(`bluebird`)
const path = require(`path`)

// Implement the Gatsby API “onCreatePage”. 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)
}
}
Loading