Using React Router On SPAs

Routing is often touted as a difficult aspect of building an app but in my experience, it’s been straightforward…fairly straightforward…actually maybe I’m speaking too soon. Let me rephrase, I did routing on an app I built and it didn’t induce as much head banging as Auth did.
React Router is a tool that handles routes in a Single Page Application through “dynamic routing” which occurs when react router implements a component based approach to routing.
React has functions for routes which are built into react-router. However an additional module still needs to be installed for web apps so, firstly, install react-router-dom. After installation, you’ll need to import whichever modules you’ll plan to utilise in your app. <BrowserRouter /> can be wrapped around your app to keep the URL and UI working in tandem with each other. It also lets you set the base path for your app.
There are many modules which can be used for routing in react but a couple of the import ones are <Link /> and <Redirect />. Link is used to link pages internally in an app. Below is an example of how I used it in mine. I imported the <Link /> module
import { Link } from "react-router-dom";
I’ve imported it into a component called NavBar which is wrapped in a <nav> tag. When the user click the relevant URL link, the link tag facilitates that page change in the UI.
export default class NavBar extends Component {
render() {
return (
<nav className="navbar">
<div>
<Link to="/">Home</Link>
<Link to="/addashop">Add A New Place</Link>
<Link to="/searchshops">Search Places</Link>
</div>
</nav>
)}};
To redirect the user, you can render a <Redirect /> component at any point in the app and it will take the user to the relevant page. You’ll need to import Redirect and add the path you’d like the the user to return to.
import { Route, Switch, Redirect, withRouter } from 'react-router-dom'render() {
return (
<div>
<NavBar
history={this.props.history}
logout{this.props.logout}/>
<Switch>
<Redirect to="/" />
</Switch>
</div>
)}
There are many more modules and additional ways to use react routes, this is a quick example.