In this React tutorial, we’ll be taking a look at React router - a specific library for handling routes within a web app. At its core, what React Router does is conditionally render certain components to display depending on the route being used in the URL (/
for the homepage).
Why use React router? It allows you to build single page web applications (SPA) with navigation. React Router uses component structure to call components, which display the appropriate information.
React router also allows the user to utilize browser functionality like the back button, and the refresh page, all while maintaining the correct view of the application.
Here’s what will be covered:
By the end of this course, you will be ready to build more advanced applications without having to do unnecessary re-rendering. You’ll also have a nice piece to showcase in your portfolio
React router is a library that allows you to handle routes in a web app, using dynamic routing. Dynamic routing takes place as the app is rendering on your machine, unlike the old routing architecture where the routing is handled in a configuration outside of a running app.
React router implements a component-based approach to routing. It provides different routing components according to the needs of the application and platform.
Here is a really simple single page app (SPA) that implements routing using React Router.
export { default as NavBar } from './NavBar';
There is one component NavBar
that appears on the top of the app and enables switching between different views namely, Home
and About
. The router.js
file is where all the routes of the SPA can be defined.
In routes.js
, first, the components, views, and required packages are imported (Line 1-5). Then all those routes are defined that the SPA can take, keeping the Home
component the default route (Line 13-15). And then all the possible routes are simply added using the following template, between <Switch>
tags:
<Route exact path="/specifiedPath" component={componentName} />
The component (componentName
) will be rendered when the "/specifiedPath"
is visited on the web app.
Importing these routes from routes.js
to index.js
file, putting them inside a <Router>
tag is all that is needed as the last step.
React Router can be installed using the npm cli utility:
> npm install react-router-dom
… and then can be imported and used inside the SPAs.
We can’t have a conversation about routing and React Router without mentioning client side and server side. Client side is the browser. Its processing happens on the local machine.
Server side is where the information is processed and then sent through to a browser.
Server-side means that the action takes place on a web server. Most JavaScript can be done without access to a web server. Client-side means that the JavaScript code is run on the client machine or the browser when we’re talking about web applications. Server-side JavaScript means that the code is run on the server which is serving web pages.
Learn React without scrubbing through videos or documentation. Educative’s text-based courses are easy to skim and feature live coding environments - making learning quick and efficient.
React Router DOM is DOM bindings for the React Router, or in simpler terms React Router for websites. In contrast, React-Router-Native is bindings for an app development environment using React Native.
To return to our web vs. native development topics, React Router come in 2 flavors, just like React:
Single page applications dynamically rewrite the web page with new data from the server, instead of the default method of the browser loading entirely new pages.
When a user clicks a link, you don’t go to an entirely new page. Instead, the new context loads inline on the same page you’re already on. So only the necessary components of the page render.
Click on Ms. Maisel:
Single page applications can make the website seem more like a native app. A lot of web pages are written as single page applications where each component renders independently.
Single page applications are where React Routing comes into play. When people use a website, there are some things they expect to work – like the back button on the browser, or the URL signifies the view they are currently looking at.
This can get complicated for the developer to build in Single Page applications. There’s a “deep link” problem. Some piece of information on a Single Page app may be buried deep underneath many components.
So, how does the developer make sure the correct URL showing that component displays in the address bar?
Through routing. React Router is a JavaScript library that provides routing capabilities to single page applications built in React.
Conceptual steps to building a single page app:
Enjoying the article? Scroll down to sign up for our free, bi-monthly newsletter.
Let’s do a quick example to see the very basics of React Router. We’ll do React Router web for our example. First, we’ll follow some operational steps to get the React Router example going, then dive into the JavaScript code in depth.
const {BrowserRouter,Route,Link} = ReactRouterDOM// Set up pages using the React Router Link element for navigation - instead of <a></a>const App = () => (<div><h1>React Router Example</h1><ul role="nav"><li><Link to="/client">Client Side</Link></li><li><Link to="/server">Server Side</Link></li></ul><div><Route path='/client' component={Client} /><Route path='/server' component={Server} /></div></div>)// Populate sample pages.const Client= () => <h3>What is client side?<body><li>Browser</li><li>Runs on local machine</li><li>React renders user interface</li><li>React Router adds clickable links</li></body></h3>const Server= () => <h3>What is server side?<li>node.js - JavaScript everywhere!</li></h3>//Render app into the root HTML DOM nodeReactDOM.render((<BrowserRouter><App/></BrowserRouter>), document.getElementById('root'));
When you run the code, you should see this output:
These links will now be clickable thanks to React Router! Now you could spruce this up and add CSS, but for this example, we’ll keep it simple.
Now, let’s dive into what is actually happening with this code:
Part 1: Render()
Function
//Render app into the root HTML DOM nodeReactDOM.render((<BrowserRouter><App/></BrowserRouter>), document.getElementById('root'));
Remember from an earlier React article about the render()
function?
Render()
is taking the logic from the React element in the JavaScript side, and displaying it in the User Interface.<BrowserRouter>
tags
<BrowserRouter>
element. Everything that gets rendered goes inside the <BrowserRouter>
element.
The app tag refers to the const App = () => App function in the JavaScript code.
Part 2: Sample Pages Section
// Populate sample pages.const Client= () => <h3>What is client side?<body><li>Browser</li><li>Runs on local machine</li><li>React renders user interface</li><li>React Router adds clickable links</li></body></h3>const Server= () => <h3>What is server side?<li>node.js - JavaScript everywhere!</li></h3>
Part 3: App Function
<Route>
tags. <Route>
tags represent links between components. Route tags are React Router syntax similar to <a>
tags in normal HTML.<div><Route path='/client' component={Client} /><Route path='/server' component={Server} /></div>
component={Client}
” tells JavaScript to link to the const Client sample pageRoute path='/client'
tells JavaScript to add “/client
” to the URL when clicking that link<ul role="nav"><li><Link to="/client">Client Side</Link></li><li><Link to="/server">Server Side</Link></li></ul>
Now that you’ve explored React Router and it’s capabilities, it’s time to start building your own React applications.
The course React Tracked: Creating Web Apps with Global State is a great project-based place to start. Throughout, you’ll be learning all the ins and outs of React and by the end you will have built a fully-functional Hacker News App that will be a great addition to your portfolio.
Happy learning!
Free Resources