Reputation: 10934
I am using React Router v4 for routing in my application. The only issue I have is the query params are ignored while navigation from one route to another. Is there a way to just replace the path and preserve the query params.
Below is my code:
<Switch>
<Route exact path="/" component={() => <Redirect to="/Route1" />}/>
<Route exact path='/Route1' component={Route1Comp} />
<Route path='/Route1/:channel/:id?'
render={(routeProps) => (
<AppMain {...routeProps} />
)}
/>
<Route exact path='/Route2' component={Route2Comp} />
</Switch>
I need the app to have a query param ?isDev=true
and want to retain across. Currently if I am on localhost:3000/Route1Comp?isDev=true
and navigate to Route2Comp
using Link
then the entire path is replaced along with query params.
Upvotes: 4
Views: 5254
Reputation: 281656
You can extend the Link component from react-router to include the search params by default like
const ExtendedLink = ({ to, children, location}) => {
return <Link to={{
pathname: to,
search: location.search
}}>{children}</Link>
}
export default withRouter(ExtendedLink)
and then use it instead of Link
<ExtendedLink to='/Route1'>Route 1</ExtendedLink>
Upvotes: 4