Intro to React Router
Key Concepts
- React Router: A routing library that allows us to conditionally render components onto the page based on the URL being displayed. React Router gives us multiple tools (components and hooks) that work wherever React is rendering.
- Client Side Routing: The separation of different components onto different “pages” in an app, each with its own unique URL. With CSR, all the routing logic is handled with JavaScript, without making additional GET requests.
1.) Installing React Router
In order to use React Router, we have to install react-router-dom:
$ npm install react-router-dom
2.) Import React Router functions into index.js file
Here, we are declaring how React Router will be used in our project:
.src/index.js
import { BrowserRouter, Route} from "react-router-dom";3.) Define Client-Side Routes using <Route> components
In the App component, <Route> will tell React to render certain components based on the current URL path. For this example, the Home component will render with the route path is just “/”
.src/components/App.js
function App() {
return (
<Route path="/">
<Home />
</Route>
);
}4.) Wrap the Entire Application with <BrowserRouter> component
We do this in order to provide all other components with React Router context features.
Get Win Feigle’s stories in your inbox
Join Medium for free to get updates from this writer.
.src/index.js
ReactDOM.render(
<BrowserRouter>
<App />
</BrowserRouter>,
document.getElementById("root") );5.) Adding additional Routes
Create additional component, for example, an About component and a Contact component:
.src/components/About.js
function About() {
return (
<div>
<h1>About!</h1>
</div>
);
}..src/components/Contact.js
function Contact() {
return (
<div>
<form>Contact form here</form>
</div>
);
}6.) Add routes for newly created components (pages)
From within index.js…
./src/index.js
function App() {
return (
<div>
<Route path="/">
<Home />
</Route>
<Route path="/about">
<About />
</Route>
<Route path="/contact">
<Contact />
</Route>
</div> );
}7a. ) Implement <Switch> or “exact”
Because all routes could potentially Include the first “/” in the URL, the Home component would render on every page. We use <Switch> to only render the first component that matches the URL path.
./src/index.js
function App() {
return (
<div>
<Switch>
<Route path="/">
<Home />
</Route>
<Route path="/about">
<About />
</Route>
<Route path="/contact">
<Contact />
</Route>
</Switch>
</div>
);
}or use:
<Route exact path="/">
<Home />
</Route>







