React Router v4 - Redirect to same route with different query params

Ebis answer did not work correctly for me. When adding the query string directly to the pathname, react router tried to match the path, resulting in not founding the route when using the Redirect component.

A workaround was to add a / before the query string like so:

<Redirect to={{ pathname: `/search/hotels/?${queryString}` }} />

However, this didn't seem right. Instead, I've added only the path to the pathname, and the query string to the search key like so:

<Redirect to={{ pathname: '/search/hotels', search: `?${queryString}` }} />

Hey you could use the object notation instead of a string literal, and pass a location object containing the new pathname you would like to redirect to example


const Topic = ({ location }) => (
   <Redirect to={{ ...location, pathname: '/topics?user=prolific' }} />
)

so using the spread operator, you retain previous properties of location, and then you can change the pathName to the one you want.

or

You could just format the query for the new route and prepend the route name, before passing it to the Redirect component. e.g.


const Topic = ({ location }) => {
   const userQuery = 'user=prolific&title=The Long Night';
   const newRoute = `topics?${userQuery}`

   return <Redirect to={newRoute} />
}

Hope that helps


The easiest solution I found was just using the location.search prop:

<Redirect from="/color-profile/quiz" to={`/quiz?${props.location.search}`} exact />

Found A Solution:

Instead of using <Redirect /> from React Router, I used history api to push a new route.

this.props.history.push(`/search/hotels?${queryString}`);

I wrapped my SearchComponent inside withRouter which is a HOC provided by React-Router and then used the history api.

Code Snippet:

import { withRouter } from 'react-router-dom';

class SearchComponent {

    // Component Code goes here

    onSubmit(){
        let queryString = "q=" + this.state.q;
        this.props.history.push(`/search/hotels?${queryString}`);
    }
}

export default withRouter(SearchComponent)