Gatsby/React Navigation

Gatsby/React Navigation
0

How do I set up my Gatsby navigation so that I can have the same Nav appear on each page, but also put each page on the Index component so that all of my content is visible to the user from the index page, similar to a single page app? Is there a best practice for doing that?

Currently, I have my Index component, and it renders my Header, About, Portfolio and Contact components, similar to the code below:

const Index = () => {
  return (
    <div>
     <Nav />
     <Header />
     <About />
     <Portfolio />
     <Contact />
    </div>
  )
}

I want all the components to be laid out in this order so that it has the look and feel of an SPA, but if you navigate to /about, I also want it to render that specific page, with a Navigation. I’ve tried using a Layout component and adding the Nav to that and it works how I want, except for it renders four Nav’s to the page on the Index site.

I hope my question makes sense.

Thanks.

You can put Nav inside your layout and wrap whatever content inside pages with your Layout.

Which means you can take out of Nav component inside your Index page.

Hi, thanks for the response! If I do it that way, then won’t I be rendering four Nav components on the Index page?

You’re saying,

// import your Nav component

const Layout = ({children}) => {
   return (
     <div>
       <Nav />
       <div>{children}</div>
     </div>
  )
}

and then

// import your Layout component
const Index = () => {
  return (
     <Layout>
       <Header />
       <About />
       <Portfolio />
       <Contact />
     </Layout>
  )
}

Doesn’t work?

As for this,

…so that it has the look and feel of an SPA, but if you navigate to /about, I also want it to render that specific page, with a Navigation.

Doesn’t Gatsby take care of that for you?
From the Gatsby docs (see link below):

Gatsby core automatically turns React components in src/pages into pages

So, then you could just do something like:
src/pages/about.js


// import your Layout component
const About = () => {
  return (
    <Layout>
       // stuff you want to put here
    </Layout>
  )
}

There’s a lot going on under the hood with Gatsby, and the power of it is that it does so much for you right out of the box.

Thank you for your response. I’ve got the functionality working the way that I want, but the problem I’m running into is that on the Index page, I want the Navbar to be one color and on every other page, I want it to be a different color. Is there a way to do this using React/Gatsby?