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.
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.
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.
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With