How do I conditionally render a component in Gatsby based on specific page?

Viewed 615

I'm building a website on Gatsby and I will like to be able to render a component conditionally based on which page I am. For example, in the footer I have a component that I don't want it to appear on the "ourcontent" page but yes for the rest of the site.

I tried doing this, which worked, however after running build gives me an error saying: "window" is not available during server side rendering.

{ window.location.pathname !== '/ourcontent'
  ? <MyComponent />
  : null
}

Im working using a Functional Component.

How would I be able to achieve this? Any help will be extremely appreciated! Thank you very much in advanced!

3 Answers

On any Gatsby page component you should have a location prop. Then you can get the pathname using props.location.pathname. Pretty sure this should work on server-side-rendering (your build) as well.

You can also use @reach/router. Here is an ultra simple example.

import { Location } from '@reach/router'


const IndexPage = () => (
  <Layout>
    <h1>Hi people</h1>
    <Location>
      {({ location }) => {
        console.log(location)
        if (location === '/') return <p>You are on the homepage {location.pathname}</p>
        return <h1> you are not on the homepage </h1>
      }}
    </Location>
  </Layout>
)

export default IndexPage

This codesandbox shows both the @reach/router and the location.pathname implmentations.

The simplest and easiest (the cleanest) way to achieve it is to use the built-in props provided by Gatsby. As you can see in their documentation, it exposes a location prop which contains all the information needed. Of course, because it's not a global browser object, such as window or document, it will be available during the server-side rendering as well as during the runtime.

You can simply:

import React from "react"
import { graphql } from "gatsby"

const Component = ({ location, data }) => {
  return location.pathname !== 'ourcontent' ? <MyComponent /> : null
}
export default Component

You can improve it by removing the ternary condition with location.pathname !== 'ourcontent' && <MyComponent />, is not needed to return a null.

Related