Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
96
rated 0 times [  98] [ 2]  / answers: 1 / hits: 27577  / 8 Years ago, tue, november 29, 2016, 12:00:00

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?


More From » reactjs

 Answers
10

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.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);

[#59887] Saturday, November 26, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jarod

Total Points: 62
Total Questions: 111
Total Answers: 83

Location: Saint Vincent and the Grenadines
Member since Sat, Sep 11, 2021
3 Years ago
jarod questions
;