snail
snail

Reputation: 119

How to switch page without click <Link> in React?

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?

Upvotes: 2

Views: 2954

Answers (4)

tal weissler
tal weissler

Reputation: 225

You can try using react's navigate:

import { useNavigate } from "react-router-dom";
const navigate = useNavigate();

navigate("/another-page")

Upvotes: 0

周星星
周星星

Reputation: 73

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)

Upvotes: 3

Muneeb
Muneeb

Reputation: 1559

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

Upvotes: 0

Nikita Madeev
Nikita Madeev

Reputation: 4380

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)

Upvotes: 0

Related Questions