How To Pass Multiple Route Parameters in a React URL Path

How To Pass Multiple Route Parameters in a React URL Path

Redirects are fairly common. Passing more than one piece of dynamic data with them is not.

Image for postThe React solution to multiple route parameters in a URL path.

Introduction

Recently, I came across an interesting problem I hadn?t encountered before. I wanted to pass more than one route parameter in a React URL route path, then access those parameters in a component upon redirect.

The reason for this problem arose when I was building a demo project to illustrate various ways to do responsive web design with ReactJS. I was using The Movie Database API to supply movie data to my React front end project.

What I wanted was for a user to see a list of movie genres (action, adventure, comedy, etc.), click on a genre, and be redirected to a list of movies that fell into that genre. Seems straightforward enough, right?

Image for postThis is what a user should see after clicking on ?Action? in the genres list: movies that are classified as ?adventure? movies.

Well, yes, it seems simple?except that the movie API supplying the list of movies based on genre required a genreId to fetch the data, while what I wanted to display to users along with the movie list was the genreName that they?d actually clicked on to generate this list. Do you see my problem?

Two different pieces of data, both required by a different, unrelated component upon redirect (so passing data through props like with a typical child component was out of the question) from the genericGenres component to the specific GenreList component displaying the movies related to that genre.

Surprisingly, when I started to look for examples of how to pass multiple route parameters in a URL path in React, I couldn?t find much.

So that?s what I wanted to share today: How to add, and later access, multiple route parameters in a ReactJS project upon redirect using react-router-dom, the most popular router for React applications.

React Routes and Route Parameters

Before I go much further, let me clarify what routes and route parameters are in ReactJS, in case you?re not familiar.

I?ll be using my demo project repo, so if you?d like to see the complete codebase or the working demo, they?re available here and here.

If you?re completely new to how routing works in ReactJS, I recommend checking out react-router-dom?s documentation first. This will not be an in-depth explanation of that, but it is the router I?m using in this article.

Routes

Routes specify the path to different components in a ReactJS application. When a user clicks a link to a page or hits a button that redirects him/her, the router renders the matching <Route /> for that component. For instance, this is what the route for the Genres page in my movie app looks like.

Traditional, static route URL in React:

Image for postThis is a static URL route in a React application.<Route exact path=”/genres” component={Genres} />

This is a static route that will always be the same, regardless of who the user is or which page they?re coming from. No matter what, whenever they click a link to go to the Genres page, this route will always be used to get them there, and it will always render the same component ? no dynamic content required.

Route parameters

Route params are parameters whose values are set dynamically in a page?s URL. This allows a route to render the same component while passing that component the dynamic portion of the URL, so that it can change its data based on the parameter.

Examples of URL route params you might recognize include things like IDs for products, books, users, or, in my case, movies. At least with React, in order to get the details for the correct item, the dynamic component would need the unique, specific ID of the item supplied, so it could get the correct data to display.

Here?s what the MovieDetailsContainer route with dynamic URL parameters in my app looks like.

Dynamic route URL in React:

Image for postThis is a dynamic route with placeholders for `:id` that will be updated on-the-fly based on user input.<Route exact path=”/movie/:id” component={MovieDetailsContainer} />

This is an example of a dynamically updating route. The first part of the path, the “/movie/? part, doesn?t change, but the :id is a route parameter that is set dynamically ? usually from a user?s actions, like clicking a link or typing an input and clicking a search button.

This is what changes and it causes the MovieDetailsContainer to be rendered with the ID of the movie included. The component then pulls this out of the URL path when it renders to get the details of that particular movie to show to a user.

Accessing dynamic route params in a component

Typically, the component being rendered on redirect will access the dynamic route info it needs from the URL.

Accessing dynamic path parameter in a URL:

Image for postThis is the object you need to access to reach the URL path in ReactJS.this.props.match.params.id

Inside a React component that needs URL path data, this is the code you?ll have to use to access the route?s actual ID, which was shown as a placeholder in the route path as :id. It?s a little verbose, I agree, but up until react-router-dom?s React hooks updates, it was what we had to use to access the data.

From there it can be set to local component state, used to fetch data, rendered out in the JSX, etc.

That is pretty much where the online tutorials stop: with a redirect example showing a single :id path param. This is where my piece picks up.

Setting up the new dynamic route path

Hopefully, we?re on the same page now. Routes are clear. Route params are clear. Accessing those parameters from a component that a user is redirected to is clear. The only thing that still remains unclear is what to do if you have more than one dynamic route parameter to add to a route path.

Knowing what I knew about React route paths in react-router-dom, I decided to try creating a route path for the GenreList component. This is the component that shows the list of movies associated with a particular genre using two dynamic parameters: :genreName and :genreId.

Note: All of my actual routing for the app was contained in the App.js file inside the src folder, for clarity.

App.js

Image for postThis is a dynamic route with placeholders for both `genreName` and `genreId` as part of the URL.<Route exact path=”/genres/:genreName/:genreId” component={GenreList}/>

This was step one of handling a route containing more than one route parameter. The next step is setting the genre ID and genre name in the Genres component.

Adding more than one route parameter to a URL

The Genres component contains, among other things, two state objects: selectedGenre (a number initially set to 0) and selectedGenreName (a string initially set to ??). These are the two pieces of state which will be set by a user clicking one of the genres listed in the list.

As soon as a user clicks a single genre, the genre?s ID and name are set in the Genres component?s state. This triggers the renderRedirect() function you see below, to redirect the user to the GenresList component, as defined by the route path.

this.state.selectedGenreName is inserted as the route placeholder :genreName .this.state.selectedGenre is replaced with the route placeholder :genreId.

Genres.js

Image for postRedirect code for including both the genre name and genre ID in the URL.renderRedirect = () => { if (this.state.selectedGenre !== 0 && this.state.selectedGenreName !== ”) { return ( <Redirect to={`/genres/${this.state.selectedGenreName}/${this.state.selectedGenre}`} /> ); }};

Step two is now complete. A particular genre ID, required by the unrelated GenreList component to fetch movies of that genre is part of the URL, and the genre name, to display which genre the user?s viewing movies for, is also included. Let?s go to the redirect component, GenreList, that now needs this data.

Accessing the route parameters from a URL

OK, last step: the component being redirected to, GenreList, needs to pull out the different pieces of the dynamic React route path. It needs the genreId to fetch the movie list from The Movie Database API, which it extracts with this.props.match.params.genreId, and it needs genreName to display in the component?s JSX , showing which genre the user clicked on, which is accessed via this.props.match.params.genreName.

Pretty cool!

GenreList.js

Image for postCode for pulling the `genreId` out of the URL for the data fetching call and the `genreName` from the URL for the display in the JSX rendered code.if (this.props.match.params) { try { const movies = await movieAPI.getMoviesByGenre( this.props.match.params.genreId, ); this.setState({ movies, loading: false }); } catch (err) { this.setState({ loading: false, error: true }); } }}render() { return ( <> <div className=”genre-search-title” onClick={() => this.props.history.push(‘/genres’)} > <div> <i className=”fa fa-chevron-left” aria-hidden=”true” /> <p>Back to Genres</p> </div> <h2>{this.props.match.params.genreName} Movies</h2> </div> <MovieList loading={this.state.loading} error={this.state.error} movies={this.state.movies} /> </> );}

I didn?t believe it could be that simple for a redirect, but it was!

Just by using the correct URL path params syntax (this.props.match.params…) and passing the corresponding variable name (genreId or genreName), I was able to pull out the correct value.

This sort of thing can be done anywhere you need dynamic data when redirecting from one unrelated component to another.

Conclusion

Dynamic redirects are a fairly common occurrence in any web application, React apps included, but despite this, tutorials illustrating them are not so easy to come by. And examples of redirects with more than one piece of dynamic data are non-existent, which is why I decided to write a piece about just that.

With the help of react-router-dom’s route paths and dynamic parameters, it really isn?t as complicated as I once thought to pass more than one piece of data from one component to another unrelated component via a redirect.

Check back in a few weeks, I?ll be writing more about JavaScript, React, ES6 or something else related to web development. Follow me so you don?t miss out!

Thanks for reading, I hope I?ve made ReactJS redirects with dynamic URL route params a little clearer and that this was something you?ll find useful in your own applications.

If you enjoyed reading this, you may also enjoy some of my other pieces:

  • Spread & Rest Parameters: JavaScript ES6 Feature Series (Pt 4)
  • JavaScript?s Async/Await versus Promises: The Great Debate
  • String Template Literals: JavaScript ES6 Feature Series (Pt 5)

References and Further Resources

  • Live demo movie website: https://movie-demo-3.paigen11.now.sh/genres/Animation/16
  • Github repo, movie website: https://github.com/paigen11/movie-demo-3
  • The Movie Database API: https://developers.themoviedb.org/3/getting-started/introduction
  • react-router-dom documentation: https://reacttraining.com/react-router/web/guides/quick-start
16