0

On my Gatsby website, I have a main header, for most pages, and a SpecialHeader for specific pages.

In my Layout file, which holds the header, page children, footer, etc, I have added this condition:

        {location.pathname === ('/special-page/' || '/special-page') ? (
          <SpecialHeader currentPathname={location.pathname} />
        ) : (
          <MainHeader currentPathname={location.pathname} />
        )}

I would like to only show the SpecialHeader for pages that include the path /special-page. Is there a better way to do this?

There will be additional subpages (/special-page/foo) that will need the same header. Is it possible to show the special header if only the /special-page path is present? For example something like /special-page*

I hope I make sense. Thanks in advance for any advice.

Kayla
  • 165
  • 2
  • 4
  • 13

2 Answers2

0

Assuming you are using react-router-dom There is a feature for optional path parameters:

  • Optional parameter
<Route path="/to/page/:pathParam?" component={MyPage} />
  • Multiple optional parameters
<Route path="/to/page/:pathParam1?/:pathParam2?" component={MyPage} />
filoscoder
  • 495
  • 1
  • 4
  • 10
0

I found the solution by removing the forward slashes and getting the first word in the path. If there was a match in the name of the path, I would should the correct header.

For example:

const stripPath = location.pathname.split('/')[1];
const isSpecialPath = stripPath === 'special-page' ? true : false;

{isSpecialPath ? (
  <SpecialHeader currentPathname={location.pathname} />
  ) : (
  <MainHeader currentPathname={location.pathname} />
)}

Kayla
  • 165
  • 2
  • 4
  • 13