Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react-router 4 does not update url with query parameters

I use higher level filter component to add query parameters to URL so that the users could share links with different types of filter.

I am exporting component withRouter() and everything seems legit - I get history injected into component props. However when I call this piece of code:

this.props.history.push({
        pathname: this.props.history.location.pathname,
        query: { tags: selectedTags }
    });

it does change the state of this.props.history and I can see my query present but the URL in browser does not change. Am I doing something wrong?

like image 880
Xeperis Avatar asked Sep 29 '17 08:09

Xeperis


People also ask

How do you programmatically update query params in React router?

Use the useSearchParams hook to programmatically update query params in React router, e.g. setSearchParams({query: 'myValue'}) . The useSearchParams hook is used to read and modify the query string in the URL for the current location. Copied!

Does React router change URL?

Using react-router-dom to Change URL Path and Render Components. The react-router-dom package is great for rendering different React components based on the url path. Therefore, React components can lead to others by changing the url path.

How do I get the current URL parameters in React?

To get the url parameter from a current route, we can use the useParams() hook in react router v5. Consider, we have a route like this in our react app. Now, we can access the :id param value from a Users component using the useParams() hook. In React router v4, you can access it using the props.match.params.id .


1 Answers

You are using it wrong, your code should be:

this.props.history.push({
        pathname: this.props.history.location.pathname,
        search: `?tags=${ selectedTags }`
    });

You can read more about navigation: https://github.com/ReactTraining/history#navigation

like image 147
Quoc-Anh Nguyen Avatar answered Nov 03 '22 08:11

Quoc-Anh Nguyen