React: React Router

Ifeoluwa Akinremi Wade
2 min readMar 13, 2022
Photo by Ildefonso Polo on Unsplash

Client-Side Routing

Client-side routing is exactly what the name describes. In my experience, I’ve used HTTP requests and the server-side to handle routing, the fetching and displaying of data on the browser. Whereas, with client-side routing, all that is handled on the client side. This makes for a speedy and seamless user experience regarding page navigation.

What Is React Router?

It is a standard library that allows for navigation through React components in the UI. Or in other words, it “allows us to link to specific URLs then show or hide various components depending on which URL is displayed” (Introduction to React Router — Flatiron School).

Why?

React Router allows for the building of a single page application. It would enable navigation without page refreshing.

How?

React Router uses the structure of components to display information.

Import BrowserRouter

BrowserRouter allows for routing in URL segments. It helps with separation of concerns by being the parent components that stores all the components you’d wish to display information from as routes.

import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';

Above, I have BrowserRouter imported as Router from react-router-dom in my App.js file.

import Home from './components/Home';
import About from './components/About';
import ParkContainer from './containers/ParkContainer';

Then I import the components I am going to use as routes to navigate from inside the browser above.

render() 
{
return (
<div>
<Router> BrowserRouter as Router
<Routes>
Components as routes along with the URL path name
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />}/>
<Route path="/test" element={<ParkContainer />}/>
</Routes>
</Router>
</div>
)
}

Link

Link is what actually allows you to navigate through the routes by setting the URL. It also keeps track of the browsing history.

import import { Link } from 'react-router-dom'

Link must also be imported into my NavBar component (I will be importing this component to be used inside BrowserRouter later.

NavBar.jsreturn (
<nav id='nav'>
<div>
<Link id="link" to="/">Home</Link>{" "}
<Link id="link" to="/about">About</Link>{" "}
<Link id="link" to="/test">TEST</Link>
</div>
</nav>
)

App.js file

import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import NavBar from './components/NavBar';
import Home from './components/Home';
import About from './components/About';
import ParkContainer from './containers/ParkContainer';
class App extends Component { render()
{
return (
<div>
<Router> BrowserRouter as Router
<Routes>
Components as routes along with the URL path name
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />}/>
<Route path="/test" element={<ParkContainer />}/>
</Routes>
</Router>
</div>
)
}
}

--

--