React Router 4.x Parameters

Chris Underwood
Mar 10 · 7 min read

While learning React.js I had trouble understanding the power of React Router, particularly the props that are passed down via routes. This is something I needed to learn and with the idea that the best way to fully learn something is to teach it, I wrote this article about what I learned. This article will cover the parameters that React Router 4.x provides us and how they can be used in your React applications.

I assume that you already know what React Router is. If you need some basics I suggest this course as refresher: https://codeburst.io/getting-started-with-react-router-5c978f70df91 .

Now, on to meat of the article.


If you are in a route generated by React Router, you will always get three props passed down: match, location, and history. If you use console.log inside any component accessed via React Router you will see something like this:

https://medium.freecodecamp.org/hitchhikers-guide-to-react-router-v4-4b12e369d10

Match

A match object contains information about how a <Route path> matched the URL.

  • params - (object) Key/value pairs parsed from the URL corresponding to the dynamic segments of the path
  • isExact - (boolean) true if the entire URL was matched (no trailing characters)
  • path - (string) The path pattern used to match. Useful for building nested <Route>s. It will have the parameter identifiers listed (e.g. path: “/:teamId/articles”).
  • url - (string) The matched portion of the URL. Useful for building nested <Link>s. It will have the URL listed in the browser navbar (e.g. url: “/foxes/articles”).

Match Examples:

URL Parameters — (example)

If you find the line <Route path="/:id" component={Child} /> you will see that if you click on the provided link for Yahoo you will see ID: yahoo below the links returned by the Child stateless functional component. You can also put was anything you want in the url navigation bar and it will be showed in the same spot. We are grabbing the parameter id that is located immediately after the root / and then located in the match.params object from the URL.

Ambiguous Matches — (example)

This is using the URL parameters piece in a more real world example. You will see 2 fixed routes and then a dynamic route. It is important to put your dynamic routes after you static routes as the dynamic route will grab everything keep you from reaching your static route(s).

Custom Link — (example)

For this example we are going to use the children feature. Unlike render, children always render on the page. The OldSchoolMenuLink is a customized version of Link and has the same behavior/properties.

Location

Locations represent where the app is now, where you want it to go, or even where it was.

It is also found on history.location but you shouldn’t use that because its mutable.

A location object is never mutated so you can use it in the lifecycle hooks to determine when & where navigation happens, this is really useful for data fetching and other processing.

  • hash - (string) A hash to put in the URL, e.g. #a-hash.
  • key - (string) A unique identifier for React Router to identify each route.
  • pathname - (string) The full URL of the current page. If there are multiple options of what can be seen on the page, this url will show the current path that shows the specific option (e.g. pathname: “/foxes/articles/Foxes-close-out-big-game”).
  • search - (string) A string representation of query parameters. The parameters start with a ?, are in pairs with the parameter being searched, an = with no spaces, and the search term. Pairs are connected with & (e.g. “?filter=top&origin=im”).
  • state - (object) If you need to add some “location state” that will be available whenever the app returns to that specific location, you can use a location object instead. This is useful if you want to branch UI based on navigation history instead of just paths (like modals).

Location examples:

Blocking Redirection & Transitions —(example)

This example uses a simple prompt to ask if a person want to navigate away from the form if the length of value in the text field is > 0. Location.pathname is displayed on the prompt to show the location where pressing the OK button will take you.

Verifying Navigation —

This can be used with nextProps or prevProps. As the example below shows, just check whether the prop versions are the same or different as your test requires.

https://reacttraining.com/react-router/web/api/location

Customizing 404 pages — (example)

There are a couple of interesting things going on here. First, I would like to point out the <Redirect from="/old-match" to="/will-match" /> in the Switch statement. While this does not directly use the location statement, it does show how we can redirect people away from a route automatically without them even knowing or being given an option even though in this case we do have a route link that specifically triggers the ‘old-match’ route. The second interesting part is that we see the location.path for non-matching routes. We cannot use Match URL or path because they do not ‘match’ an existing route.

Location & Match together:

Animated Transitions or Multiple Parameters— (example)

It is easy to get caught up in the idea that is example is about Animated Transitions but I would argue that real learning opportunity is the pattern of using multiple route parameters that are passed into a function to used to return a desired output. We can also see, like in other samples, there is a default route shown via render. The params are grabbed and sent to the proper component in the Switch near the end of functional component AnimationExample. Location.key is used to uniquely identify each transition. Match’s params object is used to grab the URL params as key value pairs as that they are accessible to use both in computing the colors via CSS but also to display on the screen as text.

History

There are lots of pieces to the history API but the most common reason you will use it is to change the URL with push(). While history has some of the same properties as Match and Location it is not best practice to limit your usage of History when other options are available as it mutable and cannot be trusted to have the data that is expected.

  • length - (number) The number of entries in the history stack
  • action - (string) The current action (PUSH, REPLACE, or POP)
  • location - (object) The current location. May have the following properties:
  • pathname - (string) The path of the URL
  • search - (string) The URL query string
  • hash - (string) The URL hash fragment
  • state - (object) location-specific state that was provided to e.g. push(path, state) when this location was pushed onto the stack. Only available in browser and memory history.
  • push(path, [state]) - (function) Pushes a new entry onto the history stack
  • replace(path, [state]) - (function) Replaces the current entry on the history stack
  • go(n) - (function) Moves the pointer in the history stack by n entries
  • goBack() - (function) Equivalent to go(-1)
  • goForward() - (function) Equivalent to go(1)
  • block(prompt) - (function) Prevents navigation (see the history docs)

History examples:

history.push(‘route’) —(example)

This is often used after an action has taken place and we want to be taken to a new location. Our example is a textbook usecase of using history.push() after a delete function. Remember that you can only use history.push() if you were sent to your current location by a route or you will not have access to the History object.

Additional Topics

Code-Splitting — (example1, example2)

Code-Splitting is the idea that we don’t want to download every component or library to the client unless it is going to be used by said client. The most common way to ‘split’ code is based on routes as that most often is what defines the components, data, and libraries that you will need. Going fully into configuration and implementation of code splitting is beyond the scope of this article, but note that the files for Home and About are not loaded until the route is actually travelled.

https://reactjs.org/docs/code-splitting.html#route-based-code-splitting

Thanks for reading. I hope you found it helpful.

Please check out my LinkedIn if you would like to know more about me.

Bibliography:

Chris Underwood

Written by

Full Stack Developer http://chrisunderwood.info https://www.linkedin.com/in/chrisunderwood7/

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade