React Router DOM - How do I enable a navigation bar on every page?

I have this code in the 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 the Link component in one of my other components, but I realized that the BrowserRouter must be the root element of the App.js component for this to work. Now I wonder how I am going to make it a route element, if I still want to include a navigation bar on every page.

+4
source share
1 answer

You can simply place it outside the component <Switch>.

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

Source: https://habr.com/ru/post/1684059/


All Articles