2

In my index.js, I have a render method with Router that contains Routes that show components:

<Router>
  <div>
    <Headers />
    <ToggleSwitch />
    <Route exact path="/" component={Home} />
    <Route path="/library" component={Library} />
    <Range />
  </div>
</Router>

This works fine.

However, on the Library route, I do not want to show either <Headers /> or <ToggleSwitch />.

So I'd like to be able to apply the following approach, for example:

const isHeaderRoute = (!route.includes('library'))

{isHeaderRoute && (
  <Headers />
  <ToggleSwitch />
)}

To do this I would presumably need access to the URL path.

How can I achieve this using React Router?

alanbuchanan
  • 3,993
  • 7
  • 41
  • 64
  • Possible duplicate of [React Router v4 with multiple layouts](https://stackoverflow.com/questions/42862028/react-router-v4-with-multiple-layouts) – csilk Aug 15 '17 at 03:53

2 Answers2

1
<Router>
  <div>
    <Route exact path="/" component={Home} />
    <Route path="/library" component={Library} />
    <Range />
  </div>
</Router>

Remove the Headers and ToggleSwitch component from the route and just put them in the Home Component.

If you want to do in the Router get the pathname by window.location.pathname and do what you have done in the example:

const isHeaderRoute = (!window.location.pathname.includes('library'))

{isHeaderRoute && (
  <Headers />
  <ToggleSwitch />
)}

window.location.pathname is a Javascript method, not a react-router method. What you have suggested is impossible in react-router because the check needs to be done outside the router where there is no way of accessing the router path which can only be accessed inside the router (by child components etc).

mrinalmech
  • 2,065
  • 1
  • 20
  • 18
1

I just came across the same issue, solving it with the same kind of answer as posted here

Wrap your <Route /> in a component that includes the <Headers /> and <ToggleSwitch /> (or vice versa, which ever makes more sense for your code)

Eg. (ES6 using react-router-v4)

const SpecialRoute = ({ component: Component, ...rest }: {component: any}) => (
  <div>
    <Headers />
    <ToggleSwitch />
    <Route
      {...rest}
      render={(props: {location: string}) => (
        <Component {...props} />
      )}
    />
  </div>
)

<Router>
  <div>
    <SpecialRoute exact path="/" component={Home} />
    <Route path="/library" component={Library} />
    <Range />
  </div>
</Router>

Further reading

csilk
  • 2,732
  • 3
  • 23
  • 40