React Router in 8 Simple Steps
If you’ve ever built a React app, chances are you’re familiar with React Router.
If you’re not, or need a refresher, React Router is basically what makes React so powerful in building single page web apps.
Through using React Router, we can manage the navigation of our web app, creating routes so that certain pages or ‘components’ appear when a user clicks on a link.
This is perfect for your header & footer as navigators for your website / web app.
Installation and Use
Follow these next few steps to get started with React Router after you’ve created a react app.
- Install react-router-dom:
npm install react-router-dom
2. In the Index.js file, import the Router:
import { BrowserRouter as Router } from "react-router-dom"
3. In the Index.js file, wrap the app component in the router:
4. Navigate to the App.js file, and import Route, Switch, and Redirect:
import { Route, Switch, Redirect } from "react-router-dom"
5. In the App.js file, import a Header, as well as any other components you want to be able to navigate between:
6. In the App.js file, render a Header above an open Switch. The Header should be OUTSIDE of the Switch. Within our Switch, create the routes to each of those pages by declaring the path (what get’s pulled from the url in a browser), and which component to load when that path gets called:
7. Create (or navigate to) a Header.js file and import Link:
import { Link } from "react-router-dom"
8. In the Header.js file, declare your Links, and the path that each link will lead to:
Each Link in our header now has an associated route, and based on what Link the user clicks, they will only see the components associated with that route.
Creating powerful and quick single page web apps has never been easier.
Thank you for checking in, and I’ll see you again soon!
Cheers!