0

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.

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 Answers2

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
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