React ~ Router ~ Programmatically Navigate - rohit120582sharma/Documentation GitHub Wiki

The typical use case for routing programmatically is routing on some sort of user event that isn’t a Link click.

There are two ways to programmatically navigate with <Redirect /> and history.push.



React Router (v4)

<Redirect />

The primary way you programmatically navigate is by using a <Redirect /> component. It is composable and declarative.

class Register extends React.Component {
    state = {
        toDashboard: false
    };
    handleSubmit = () => {
        setTimeout(() => {
            this.setState({ toDashboard: true });
        }, 1000);
    }
    render() {
        if (this.state.toDashboard === true) {
            return <Redirect to='/dashboard' />
        }
        return (
            <div>
                <h1>Register</h1>
                <Form onSubmit={this.handleSubmit} />
            </div>
        );
    }
}

History

The real workhorse of React Router is the History library which is a JavaScript library that lets you easily keeping track of session history for React Router.

When React Router renders a component, it’ll pass that component three props: location, match, and history. This history prop comes from the History library and has a ton of fancy properties on it related to routing. history.push pushes a new entry into the history stack - aka redirecting the user to another route.

class Register extends React.Component {
    handleSubmit = (user) => {
        setTimeout(() => {
            this.props.history.push('/dashboard');
        }, 1000);
    }
    render() {
        return (
            <div>
                <h1>Register</h1>
                <Form onSubmit={this.handleSubmit} />
            </div>
        );
    }
}

withRouter

If Register component is not rendered by React Router, then we won’t have access to history, match, and location props, which means we also won’t have access to history.push.

To fix this and get access to those props, you can use the withRouter higher-order component.

import { withRouter } from 'react-router-dom';
class Register extends React.Component {
    ...
}
export default withRouter(Register);


React Router (v5)

The primary way you programmatically navigate is by using a <Redirect /> component. It's same like React Router (v4).

The other way is History library. In order to get access to history, you use the useHistory custom Hook. This history object has a ton of fancy properties on it related to routing. In this case, the one we’re interested in is history.push. What it does is it pushes a new entry into the history stack - redirecting the user to another route.

import React from 'react';
import { useHistory } from 'react-router-dom;

function Register () {
    const history = useHistory();

    return (
        <div>
            <h1>Register</h1>
            <Form afterSubmit={() => history.push('/dashboard')} />
        </div>
    );
}
⚠️ **GitHub.com Fallback** ⚠️