1

I'm trying to toggle a few components based on route. I do get it to work on a refresh but not a navigate. Anybody know what I'm missing and doing wrong here?

import { BrowserRouter as Router, withRouter } from "react-router-dom";

class App extends Component {
  render() {
    return (
      <Router>
        <div className="App">
          pathname: {(this.props.location.pathname)}
          {!this.props.location.pathname.includes('/target') ? <TopBar childProps={childProps} /> : null}
          {!this.props.location.pathname.includes('/target') ? <Header /> : null}
          {this.props.location.pathname.includes('/target') ? <SecondaryHeader /> : null}
            <Routes childProps={childProps} />
          <Footer />
        </div>
      </Router>
    )
  }
}

export default withRouter(App)
Dejan.S
  • 18,571
  • 22
  • 69
  • 112

1 Answers1

2

There is a component exported from react-router-dom which is called Route, and it encapsulates exactly the logic you want.

Conditionally renders components based on the current path

<Router>
    <Route path='/target' render={() => <MyComponent />} />
    <Route exact path='/target' render={() => <AnotherComponent />} />
</Router>
  • render accepts a function which returns some jsx (you can also use component, see the differences here).

  • path is the path that window.location.pathname must match to render what is being passed to render or component

  • exact is whether or not the path must be absolute.

Imagine that the current path is /target/foo. In this case MyComponent will be rendered but AnotherComponent won't.

You can also pass a regex to path, see the full docs here

Dupocas
  • 20,285
  • 6
  • 38
  • 56