0

In some case I need to switch page without click anything. makes me click some btn, url and so on. Also I don't want to reload a page. Is there any solution?

snail
  • 99
  • 2
  • 9
  • Are you using a particular router? Assuming you're using the most common, react-router, this is duplicate of: [Programmatically navigate using react router](https://stackoverflow.com/questions/31079081/programmatically-navigate-using-react-router) – DBS Jun 04 '20 at 09:21

3 Answers3

2

I think you need React-Router.

You can switch page like this(if use React-Router):

this.props.history.push('/index');

You should use withRouter if your component don't hava history in props.

function Page(props) {
    function handleClick() {
        props.history.push('/index')
    }
    return (<p onClick={handleClick}>index page</p>)
}

export default withRouter(Page)
周星星
  • 61
  • 3
0

https://reacttraining.com/react-router/web/api/history

// usually all you need
<Link to="/somewhere"/>

// but you can use a location instead
const location = {
  pathname: '/somewhere',
  state: { fromDashboard: true }
}

<Link to={location}/>
<Redirect to={location}/>
history.push(location)
history.replace(location)
Nikita Madeev
  • 4,284
  • 9
  • 20
0

If you are using react-router v4, you can do it like this it won't reload the page.

this.props.history.push('/foo')

For earlier versions

this.props.router.push('/foo')
Muneeb
  • 1,469
  • 16
  • 24