How to pass and read query parameters from one page of your application to another by using the React Router

In this post we are going to see how you can register a new route in your React application and then pass information with the help of query parameters from one subpage to another.

Let us suppose the following scenario. You have page that contains a list of products with some basic information. You want to be able to click on an item of this list and navigate to a details-page, where the user can find more details about a specific product.

The following code examples are written in TypeScript. Visual Studio provides a great starting template for your React projects. I used the 4th generation of the React Router

First we need two routes for the scenario we just mentioned. The first route loads all the products, with only a limited information for each of them, from our backend and the second one loads the all the details to one product:

export const routes = <Layout>
    <Route exact path='/' component={ Home } />
    <Route path='/products/:id' component={ProductItem} />
    <Route path='/products/' component={ProductsList} />
</Layout>;

As you can see, we first define the more specific route and then the general one, so that the picking of the correct route works like expected, since the order matters.

In our ProductsList component we are defining a link for each item in our list:

{this.props.products.map(product => {
    return <li key={product.id}>
            <Link to={`/products/${product.id}`}>{product.name}</Link>
           </li>;
    })
}

here we iterate over the products we got from our backend and by using the map function we are creating for each one of them a new list item. product.id is the unique id of each product.

In the ProductItem component we have to read this id, so that we load the appropriate information from our servers.

componentWillMount() {
    let { id } = this.props.match.params as any;
    this.props.requestTickets(id);
}

componentWillMount is a reserved method in React, belongs to the component’s lifecycle and runs when the component is first added to the current page.

The let { id } = this.props.match.params as any; line does all the magic for us. Pay attention to the way we use object destructuring for getting the query parameter named id from the params object. Apart from that we cast the result to any, since TypeScript cannot find any definition for id (only available in runtime) and throws a compiler error if we do not use this approach.

In case you have more than one query parameters you want to read, just follow the same principle and get their values from the params object.

If you have any thoughts or questions about this article, just write me a comment. Do not hesitate to contact me.

comments powered by Disqus