paint-brush
Beginners Guider To React Routerby@melbeavs_
362 reads
362 reads

Beginners Guider To React Router

by melbeavs_July 1st, 2020
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

React Router is the standard routing library for React using dynamic routes, which means that the routing takes place whenever React is rendering. The props history, match, and location are included in each component that uses React Router. The match object contains information about how a component inside Route matches the URL, it is formed by 4 keys: true/false: (true/false): it will return true if the entire URL was matched. The location object brings information about where the app is now, where you want it to go, and where it was created.

Company Mentioned

Mention Thumbnail
featured image - Beginners Guider To React Router
melbeavs_ HackerNoon profile picture

Today I decided to write about the props history, match, and location that are included in each component that uses React Router. But first, to start warming up here is a simple definition of React Router:

React Router is the standard routing library for React using dynamic routes, which means that the routing takes place whenever React is rendering.

How it works

After using

npx create-react-app

for creating my app, and install react-router-dom with

npm install react-router-dom

I was able to create the following components with their corresponding routes with the help of this incredible source:

App.js

import React from ‘react’;
import { 
BrowserRouter as Router,
Switch,
Route,
Link
} from “react-router-dom”;
import Home from ‘./Home’;
import Dashboard from ‘./Dashboard’;
import About from ‘./About’;
function App() {
 return (
  <Router>
    <div> 
      <ul>
        <li>
          <Link to=”/”>Home</Link>        
        </li>
        <li>
          <Link to=”/about”>About</Link>
        </li>
        <li>
          <Link to=”/dashboard”>Dashboard</Link>
        </li>
      </ul>
      <hr />
      <Switch>
        <Route exact path=”/”>
          <Home />
        </Route>
        <Route path=”/about”>
          <About />
        </Route>
        <Route path=”/dashboard”>
          <Dashboard />
        </Route>
      </Switch>
    </div>
  </Router>
  );
}
export default App;

Home.js

import React from ‘react’;
function Home() {
  return (
    <div>
      <h2>Home</h2>
    </div>
  );
}
export default Home;

About.js

import React from ‘react’;
function About() {
  return (
    <div>
      <h2>About</h2>
    </div>
  );
}
export default About;

Dashboard.js

import React from ‘react’;
function Dashboard() {
  return (
    <div>
      <h2>Dashboard</h2>
    </div>
  );
}
export default Dashboard;

If you are using Chrome and you have the extension React Developer Tools (if you don’t have it, go for it, I promise you it would be worth it), you can see all the props that our components are receiving, including 3 named: Match, Location, and History.

You may wonder where do these props come from and how can they be useful. In this article, we are gonna talk a little bit about this.

Match

The match object contains information about how a component inside Route matches the URL, it is formed by 4 keys:

  • isExact: (true/false): it will return true if the entire URL was matched. For example, if we remove the word “exact” in the Home component because path=”/” it will display always, regarding the route, being the isExact value “false”.
  • params: key/value pairs parsed from the URL corresponding to the path. One common use for it is when we want to use URL parameters to render the same component based on its URL, for example, a Users component in which every user as a particular id 1,2,3. We use params to store the value of that id.
<Route path=”/users/:id”>
  <Users />
</Route>
  • path: the path we wrote to match. To render the component About we used the path ‘/about’
  • URL: the matched portion of the URL. Sometimes it would be different than the path, for example, if we are using URL parameters our path would be:
path=”/users/:id”

and our URL for user number 1 would be:

URL=”/users/1

Location

The location object brings information about where the app is now, where you want it to go, and where it was.

If we saw our React Developer Tools again, you can see there are two locations object: One inside history, and one that stands separate.

Even though they look the same, you shouldn’t use the one inside history, because it is mutable. and the one alone is not, meaning you can use it in the lifecycle hooks to determine when navigation happens. This is useful for data fetching or DOM side effects.

One use for this is to check if the name of a path has changed for example

componentDidUpdate(prevProps, prevState, snapshot){
 if (prevProps.location.pathname !== this.props.location.pathname){
   //Do something
 }
}

You can also use locations instead of strings to the various places that navigate:

In our example, we can change

<Link to=”/about”>About</Link>

to :

const location = {
pathname: ‘/about’,
state: { fromDashboard: true }
}
<Link to={location}>About</Link>

History

A history object allows you to manage and handle the browser history inside the views or components. It usually contains the following:

  • length: is the number of entries in the history stack.
  • action: The current action performing. it says how you got to the component. (push, replace or pop).
  • location: The current location, it can have the properties: pathname, search, hash, and state. Remember it is mutable.
  • push(path, [state]): (function), pushes a new entry onto the history stack.
  • replace(path, [state]): (function), replaces the current entry on the history stack.
  • o(n): (function), moves the pointer in the history stack by n entries.
  • goBack(): (function), equivalent to go(-1). It lets us go back to the previous screen in the navigator.
  • goForward(): (function,) equivalent to go(1).
  • block(prompt): (function), prevents navigation.

One common example to use history is when we want to redirect to a component after an action executes. In this case, you cannot use Link, so history.push() comes handy. For example, you can redirect a user after logging out to the main page of your App the following way:

const handleLogout = history => () => {
  //perform action for logging out and aftewards we use:
  history.push('/main');
};

Also, you can use

history.replace("/my-path")

which would be the equivalent of :

<Redirect to="/my-path"/>

I hope you like it and found this useful!

Happy coding!