Gatsby redirect to home page instead of displaying 404 page
Other answers here will eventually fail because the window
object is not defined at build time.
Use this instead. The useEffect
hook is equivalent to componentDidMount
.
import { useEffect } from 'react';
import { navigate } from "@reach/router"
export default () => {
useEffect(() => {
navigate('/your-redirect/');
}, []);
return null;
};
You can do the following:
import React from 'react'
import { Redirect } from '@reach/router'
const NotFoundPage = () => <Redirect to="/" />
export default NotFoundPage
Gatsby creates 404 page from src/pages/404.jsx
(or 404.js
if you are not using jsx
extension). So, creating a component which redirects to the home page there should do trick, something like this:
import React from 'react';
export default function NotFound() {
if (typeof window !== 'undefined') {
window.location = '/';
}
return null;
}
You can also do it with navigate()
(formerly navigateTo()
, thanks @pgarciacamou)
import React from 'react'
import { navigate } from 'gatsby'
const NotFoundPage = () => {
return navigate('/')
}
export default NotFoundPage