I'm using ReactiveSearch search components to build a nice UI for my search app. I'm using the prop onQueryChange to invoke a function that uses to route to the search results page after user has submitted a search query.
How can I use React Router v4's to redirect to search results page after user has submitted query with the DataSearch component?
So far I have
<DataSearch
..
onQueryChange={
(prevQuery, nextQuery) => {
console.log("prev query: ", prevQuery);
console.log("next query: ", nextQuery);
{ nextQuery !== '' &&
<Redirect to="/results"/>,
}
}
}
I looked here and tried to change it for my use case. However, its not working.
UDPATE:
In regards to my comment below. I remembered that I had asked a similar question before, so I went to my profile to see if I could find it and I did. I combined that info with this and I believe I was able to come up with the solution:
if (redirect) {
return <Redirect to={{
pathname: '/search',
state: { pathname: this.state.redirect }
}}/>
}
For redirection it would be better to use onValueSelected
(docs) since query would change everytime you type something in the searchbox (in order to fetch the suggestions).
In order to handle redirection declaratively with React router 4, you would update the state
of your parent component when a value is selected and conditionally render the Redirect
component from react router. For example,
class Main extends Component {
state = {
redirect: false
};
render() {
const { redirect } = this.state;
if (redirect) {
// when this renders it would redirect to the specified route
return <Redirect to="/search" />;
}
return (
<ReactiveBase
...
>
<DataSearch
...
onValueSelected={(value, cause, source) => {
// just setting the redirect state to true for redirection
this.setState({
redirect: true
});
}}
/>
</ReactiveBase>
);
}
}
An alternate way would be to use withRouter
higher order component from React Router but the above method would also work.