Abdullah Hamzic
Abdullah Hamzic

Reputation: 529

React Router DOM — How to include a navigation bar on every page?

I have this code in my App.js component:

render() {
        return (
            <div>
                <Navbar/>
                <BrowserRouter>
                    <Switch>
                        <Route exact path="/" component={Home}/>
                        <Route path="/about" component={About} />                         
                        <Route path="*" render={() => <Redirect to="/" />} />
                    </Switch>
                </BrowserRouter>
            </div>
        );
    }

Now I tried to include a Link component in one of my other components, but I figured out that the BrowserRouter has to be the root element of the App.js component, in order for that to work. Now I wonder how I would go about making it the route element, if I still want to include the navigation bar on every page.

Upvotes: 15

Views: 20758

Answers (1)

ivarni
ivarni

Reputation: 17878

You should be able to just place it outside the <Switch> Component.

<BrowserRouter>
    <div>
        <Navbar/>
        <Switch>
            <Route exact path="/" component={Home}/>
            <Route path="/about" component={About} />                         
            <Route path="*" render={() => <Redirect to="/" />} />
        </Switch>
    </div>
</BrowserRouter>

Upvotes: 16

Related Questions