Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 268
Abdullah Hamzic Avatar asked Aug 20 '17 10:08

Abdullah Hamzic


People also ask

How do I add a navbar to my react router?

You can use the rfce command to set up the template for this as well. Next, make sure to import the elements you want in your router, as well as BrowserRouter, Routes, and and Route from react-router-dom. Now, you're going to set up your router template with a route for each element you want to have in your navbar.

How do you navigate between pages in react with react router?

Using links to switch pages js file, add the following code: import React, { Fragment } from "react"; import "./index. After importing Link , we have to update our navigation bar a bit. Now, instead of using a tag and href , React Router uses Link and to to, well, be able to switch between pages without reloading it.

What is the BrowserRouter /> component?

BrowserRouter: BrowserRouter is a router implementation that uses the HTML5 history API(pushState, replaceState and the popstate event) to keep your UI in sync with the URL. It is the parent component that is used to store all of the other components.


1 Answers

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>
like image 116
ivarni Avatar answered Oct 21 '22 21:10

ivarni