alanbuchanan
alanbuchanan

Reputation: 4173

Do not render certain components on certain routes

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?

Upvotes: 2

Views: 1881

Answers (2)

csilk
csilk

Reputation: 2952

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

Upvotes: 1

mrinalmech
mrinalmech

Reputation: 2175

<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).

Upvotes: 1

Related Questions