How to redirect from the index page to a route which is generated programmatically, in a Gatsby.JS project
Asked Answered
N

2

9

I want to reroute the index / to /blog in a gatsby project. The page at /blog route is generated inside gatsby-node.js file.

What I tried is importing Redirect from @reach-router and inside the Index component returning Redirect to='/blog' but this results in Uncaught RedirectRequest error.

The index.js file:

import React from 'react'
import { Redirect } from '@reach/router'


class BlogIndex extends React.Component {
  render() {
    return (
      <Redirect to={`/blog`} />
    )
  }
}

export default BlogIndex

Error

Novelette answered 25/2, 2019 at 16:18 Comment(0)
A
15

From @reach/router docs:

Redirect works with componentDidCatch to prevent the tree from rendering and starts over with a new location.

Because React doesn’t swallow the error this might bother you. For example, a redirect will trigger Create React App’s error overlay. In production, everything is fine. If it bothers you, add noThrow and Redirect will do redirect without using componentDidCatch.

Add a noThrow tag seems to solve this:

<Redirect noThrow to="/topath" />

You could also ask Gatsby to do this for you, in gatsby-node.js:

exports.createPages = ({ actions }) => {
  const { createRedirect } = actions

  createRedirect({
    fromPath: `/`,
    toPath: `/topath`,
    redirectInBrowser: true,
    isPermanent: true,
  })
}

See more here.


I'd add this redirect rule to where the site is hosted as well.

Artistic answered 27/2, 2019 at 5:28 Comment(0)
J
10

Use this instead. The useEffect is the React hook equivalent to componentDidMount.

import { useEffect } from 'react';
import { navigate } from 'gatsby';

export default () => {
  useEffect(() => {
    navigate('/blog/');
  }, []);
  return null;
};
Jailhouse answered 21/5, 2019 at 22:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.