How to redirect to a new page from a function in React?

If you use the react-router-dom package you can wrap your component with a router and then you have the ability to redirect the user programmatically, like so this.props.history.push('/login').

Eg:

import {withRouter} from 'react-router-dom';

class Component extends React.component {

    constructor(props){

    }

    componentDidMount(){
        this.props.history.push('/login');
    }

}

export default withRouter(Component);

See: https://www.npmjs.com/package/react-router-dom.

Leave a Comment