user8537567
user8537567

Reputation:

React Router 4 organizing routes

I'm currently trying to organize routes in my first React app using Router 4. The goal is to have some components opened (displayed) with the Navbar remaining on the page and some without the Navbar. I started with the idea of having all the components displayed under the NavBar container and it works just fine but now I need to add some links that open the linked components in the same window but without the Navbar. Maybe someone has an idea how to set such routing.

My current code:

 render() {

    return (
     <BrowserRouter>      
      <div className="App">   
        <div className="App-header">
        <h2>{this.state.title}</h2>
        <NavBar></NavBar>
        </div>
            <Switch>
              <Route exact path = "/" component = {Home} />
              <Route exact path = "/about" component = {About} />
              <Route exact path = "/register" component = {RegForm} />
            </Switch>    
       <footer className = "Footer"><Content /></footer>
       </div>
     </BrowserRouter>
    );

  }

Upvotes: 3

Views: 1794

Answers (1)

Chase DeAnda
Chase DeAnda

Reputation: 16441

You need to split up your routes into a Main section that will have the nav and then ones that don't:

render() {
    return (
        <BrowserRouter>
            <Switch>
                <Route path="/page-outside-nav" component={OutsideNav} />
                <Route path="/" component={Main} />
            </Switch>
        </BrowserRouter>
    );
}

const Main = () => (
    <div className="App">
        <div className="App-header">
            <h2>{this.state.title}</h2>
            <NavBar></NavBar>
        </div>
        <Switch>
            <Route exact path = "/" component = {Home} />
            <Route exact path = "/about" component = {About} />
            <Route exact path = "/register" component = {RegForm} />
        </Switch>
        <footer className = "Footer"><Content /></footer>
    </div>
);

The switch in your main App will first try to match routes that should exist outside the nav. If it doesn't find a match, it will fall through to main by matching <Route path="/" component={Main} />. Main should then have it's own Switch to handle routes that should exist under the nav.

Upvotes: 3

Related Questions