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.

ChrisG
  • 8,206
  • 4
  • 20
  • 34
Alex94
  • 45
  • 2
  • 9
  • Possible duplicate of [Programmatically navigate using react router](https://stackoverflow.com/questions/31079081/programmatically-navigate-using-react-router) – ChrisG 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
  • 29,321
  • 31
  • 106
  • 146
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
  • 782
  • 1
  • 12
  • 29