Search code examples
urlpathgatsbycustom-error-pages

In Gatsby how to identify if current page being rendered is 404?


In src/pages I've setup a 404.js page per the docs "Adding a 404 Page". Within this file I'm calling my Layout component and also passing in location props.

In my Layout.js file I'm trying to conditionally render some components based on wether the current page is a 404. In my testing the location object doesn't render a boolean for this, example testing with the browser asdsada:

hash: ""
host: "localhost:8000"
hostname: "localhost"
href: "http://localhost:8000/asdsada"
key: "initial"
origin: "http://localhost:8000"
pathname: "/asdsada"
port: "8000"
protocol: "http:"
search: ""
state: null

I was unable to find a way to do this after reading:

In Gatsby is there a way to identify if the current page being rendered is the 404 page so I can ternary a component?


Solution

  • You should pass a boolean in your src/pages/404.js to your Layout like:

    import React from "react"
    import Layout from "../components/layout"
    
    const NotFoundPage = () => (
      <Layout is404Page={true}>
        <div>Your Content</div>
      </Layout>
    )
    
    export default NotFoundPage