Lai32290 Lai32290 - 7 days ago 5
React JSX Question

How to redirect page with Javascript in React-Router?

I using

react-router
in my application.

In my login page, I needing authentication with
ajax
and redirect if success.

Some like following code:

class PageLogin extends React.Component {
login() {
// How to can I redirect to another page if auth success?
}

render() {
return (
<div className="login-page">
<form action="">
<div className="form-group">
<label>Username:</label>
<input type="text"/>
</div>
<div className="form-group">
<label>Password:</label>
<input type="text"/>
</div>
<div>
<button onClick={this.login}>Login</button>
</div>
</form>
</div>
)
}
}


In my
login
function, how to can I redirect to another page if authentication success?

Answer

Context is the best option, however official documentation tells that you can also use withRouter to put router prop to your component that would correctly perform history state transition:

import { withRouter } from 'react-router';

class PageLogin extends React.Component {
    login() {
        this.props.router.push('/some/location');
    }

    render() {
        return (
            <div className="login-page">
                <form action="">
                    <div className="form-group">
                        <label>Username:</label>
                        <input type="text"/>
                    </div>
                    <div className="form-group">
                        <label>Password:</label>
                        <input type="text"/>
                    </div>
                    <div>
                        <button onClick={this.login}>Login</button>
                    </div>
                </form>
            </div>
        )
    }
}

export default withRouter(PageLogin);