After clicking the search button, I can filter my database, but at the same time I would like to redirect to another route where I can show the results of the query in a table. Is this possible in React? I am using <BrowserRouter>
. That would be also great if I could redirect from the onClick event.
Asked
Active
Viewed 3,053 times
0

Alex94
- 65
- 2
- 10
-
Possible duplicate of [Programmatically navigate using react router](https://stackoverflow.com/questions/31079081/programmatically-navigate-using-react-router) – Sep 28 '18 at 10:49
2 Answers
0
Yes that is possible in React. Using history.push
install history module
npm install --save history
and then import it and do something like below in your onclick event handler
import createHistory from 'history/createBrowserHistory'
const history = createHistory()
onClickEventHandler = () => {
history.push("/path");
}
or use context.router to navigate like
this.context.router.push('/path');

Hemadri Dasari
- 32,666
- 37
- 119
- 162
-
Hi, using this.context.history i receive Cannot read property 'push' of undefined. Do I have to import something? Thank you! – Alex94 Sep 28 '18 at 10:55
-
@Alex94 Sorry my bad it is actually this.context.router.push('/path'); I updated my answer please give a try – Hemadri Dasari Sep 28 '18 at 10:57
-
this.context.router.push('/path'); well, do I need npm i --save history for this? I get TypeError: Cannot read property 'push' of undefined – Alex94 Sep 28 '18 at 11:01
-
-
-
-
Are you using react-router-redux module? do you have redux actions used in your component? – Hemadri Dasari Sep 28 '18 at 11:03
-
0
Way 1.
You can use state variable and redirect to relevent page also you can pass params and you can get it inside the component
import { Redirect } from 'react-router-dom';
if (this.state.page === 'SEARCH') {
return <Redirect to="/searchPage" />;
} else if (this.state.page === 'DETAIL') {
return <Redirect to="/detailPage" />;
} else {
return 'render component here'
}
Way 2 :- You can redirect through context also like below and similarly you can pass object as parmas as a second parameter and you need to context in constructor also Import PropTypes in your component
import { PropTypes } from 'prop-types';
Add Context Types under your component
static contextTypes = {
router: PropTypes.object
}
Call constructor with context
constructor(props, context) {
super(props, context);
}
In code method you can call below code to navigate to another page
this.context.router.history.push('/searchPage');
For both the option you don't need Redux

Abdul
- 942
- 2
- 14
- 32
-
Hi there, I get: TypeError: Cannot read property 'history' of undefined – Alex94 Sep 28 '18 at 11:13
-
static contextTypes = { router: PropTypes.object } Add this in your component and check Updated answer for reference – Abdul Sep 28 '18 at 11:15
-
Way 1: 'Redirect' is not defined react/jsx-no-undef, maybe I need this: import { Redirect } from 'react-router' – Alex94 Sep 28 '18 at 11:21
-