Shamoon
Shamoon

Reputation: 43491

How can I render a container / component based on the route using react-router?

My routes.jsx looks like

return (
  <Route path='/' component={Main}>
    <IndexRoute
      component={Home}
      onEnter={onSearchEnter}
      onChange={(prevState, nextState) => onSearchEnter(nextState)}
    />

    <Route path='privacy' component={Privacy} />
    <Route path='terms' component={Terms} />
    <Route path='dmca' component={DMCA} />

    <Route path='clips/:clip' component={Clip} />
  </Route>
)

Within my Main, I have something like:

  render () {
    return (
      <div className={`main__container ${get(this, 'props.children.type.parentClassName')}`}>
        {(() => {
          return (
            <Nav
              downloadLinks={this.props.downloadLinks}
              search={this.props.search}
            />
          )
        })()}

However, I don't want to render the Nav component if I'm in the clips/:clip route.

I'm using react-router

Upvotes: 0

Views: 986

Answers (1)

Vidup
Vidup

Reputation: 113

You should use the location prop that's passed by react-router to your Main container.

It's an object in which you can find the current pathname. I'd do something like this:

isNavVisible = (location) => {
   return location.pathname.split('/')[1] !== 'clips';
   // location.pathname would be '/clips/someClipID'
   // => location.pathname.split('/') would be ["", "clips", "someClipID"]
}

render () {
  return (
  <div className={`main__container ${get(this, 'props.children.type.parentClassName')}`}>
    {this.isNavVisible(this.props.location) &&
      <Nav
        downloadLinks={this.props.downloadLinks}
        search={this.props.search}
      />
    }
   ...
}

Upvotes: 2

Related Questions