sai
sai

Reputation: 49

How to redirect to home page(in jsx) after logout in react

<li>
    <a href="homepage.jsx">
      <i className="fa fa-sign-out pull-right"></i> 
      Log Out
    </a>
</li>

I am having homepage component in homepage.jsx, after clicking on logout i need to go to homepage component.

Help me in this.

Upvotes: 1

Views: 18940

Answers (3)

Sandeep Jain
Sandeep Jain

Reputation: 1262

Calling function to redirection on Logout button clicked on jsx component header.jsx below code redirect to login page

logoutCall = () => {
    window.localStorage.clear();
};  
goLogin = () => {
   window.localStorage.clear();
   <Link to="/login"></Link>
  };    


<Link className="linkLogoutClass" to="/login" onClick={this.logoutCall}><img style={{cursor: 'pointer'}} className="logoutImageStyle " src={logout} onClick={this.goLogin}   ></img> Logout</Link>

Upvotes: 0

Mayank Shukla
Mayank Shukla

Reputation: 104359

You are using react-router, so instead of using a and href use Link, write it like this:

<li>
    <Link to="/">
        <i className="fa fa-sign-out pull-right"></i> 
        Log Out
    </Link>
</li>

Since Homepage component is your indexroute, so navigation to / will render it.

If you want to navigate dynamically means inside any function, then check this answer:

Programmatically navigating in React-Router v4

Upvotes: 3

WitVault
WitVault

Reputation: 24120

I am assuming you are using react-router v 2.x.x. You can create a component like below for this.

Your route should also contain the route to which you want to redirect.

   <Route path="/" component={App}>
       <Route path="/homepage" component={Homepage}/>
   </Route>

class Logout extends React.Component {

    static contextTypes = {
        router: React.PropTypes.object.isRequired
    };

    constructor(props, context){
        super(props, context);
        this.state = {
            error:null
        };
    }

    logOut() {
        Api.logOut().then(
            () => {
                this.context.router.replace('/homepage');
            },
            () => {
                this.setState({
                    error:'Error occured while logging out. Please try again.'
                });
            }
        );
    }

    render(){

        return (
       <li>
          <a onClick={this.logOut} >
             <i className="fa fa-sign-out pull-right"></i> 
             Log Out
          </a>
       </li>
        )
    }
}

ReactDOM.render(<Logout/>, document.getElementById('app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id='app'/>

Upvotes: 1

Related Questions