How to redirect a page using Javascript in a React-Router?

I am using react-router in my application.

On my login page, I need authentication with ajax and redirect if successful.

Some people like the 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 can I redirect to another page if authentication succeeds?

+6
source share
2 answers

Context is the best option, however the official documentation says that you can also use withRouter to add a router prop to your component that correctly completed the transition of the history state:

 import { withRouter } from 'react-router'; class PageLogin extends React.Component { login() { this.props.history.push('/some/location'); // for react-router@3 it would be 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); 
+6
source

You will have a link to the router in context. You can simply call router.push with a new redirect path .

 class PageLogin extends React.Component { login() { this.context.router.push('/newPath'); } ... } PageLogin.contextTypes = { router: React.PropTypes.object } 

If you don't want to click a route on your history, but replace your current route instead , you can call replace instead . The API is identical to push .

+1
source

Source: https://habr.com/ru/post/1012732/


All Articles