1

I am stuck with some issue related to react-router Navigation. In my navigation there are 2 menu login and register, and my index page is login.

On login page after entered the value of emaild and password and submitting login button it get output as sessionValue.My sessionValue is username which return from serverSide and it redirect to TodoApp page. After login it redirected to TodoApp page. I want to display logout menu instead of login in navigation.

My code is as below:

app.jsx

    ReactDOM.render(
  <Router history={browserHistory}>
    <Route path="/" component={Main}>
        <Route path="RegistrationForm" component={RegistrationForm}/>
        <Route path="todoapp/:sessionValue"component={TodoApp}/>
        <IndexRoute component={Login}/>
    </Route>
  </Router>, 
  document.getElementById('app')
);

Navigation component

I tried this by using localstorage but it doesn't work. It works only when I clicked on backward arrow of browser.

 var Nav= React.createClass({
        render:function(){
            var strUserName = localStorage.getItem('sessionValue');
            console.log(strUserName);
        function loginMenu(){
                if(strUserName){

                                return <Link to="/RegistrationForm" activeClassName="active" activeStyle={{fontWeight: 'bold'}}>Logout</Link> 

            }
            else{
                return <IndexLink to="/" activeClassName="active" activeStyle={{fontWeight: 'bold'}}>LogIn</IndexLink> 

            }
        }
            return(
                <div className="top-bar">
                        <div className="top-bar-left">
                            <ul className="menu">
                            <li className="menu-text">
                                React App
                            </li>
                            <li>
                                {loginMenu()}
                            </li>
                            <li>
                                    <Link to="/RegistrationForm" activeClassName="active" activeStyle={{fontWeight: 'bold'}}>Signup</Link>
                            </li>

                            </ul>
                        </div>
                        </div>
                );
        }
        });
 module.exports=Nav;

login page (login.jsx)

if(validForm){
        axios.post('/login', {
        email:this.state.strEmail,
        password:this.state.strPassword
        })
        .then(function (response) {
        //console.log(response.data);
        var sessionValue=response.data;
//After login todoApp page is open and with session value.session value passed through url to todoApp.
        browserHistory.push(`todoapp/${sessionValue}`);
        localStorage.setItem('sessionValue',sessionValue);
 })
        .catch(function (error) {
        console.log(error);
        });
    }
}, 

Questions:

  1. how to show/hide login/logout menu.
  2. after login show logout menu and when we click on logout menu show login menu
4
  • What are you using to manage state? None of your code snippets are showing any state management. You will probably want to load your localstorage contents into state in a componentWillMount lifecycle callback. Commented May 16, 2017 at 2:57
  • My session value come from server side in callback function in handleSubmit function which is in login component. Commented May 16, 2017 at 4:55
  • And I tried to store value in local storage. I get that value in NAV component also. When I click on login(submit) button it doesn't work. But when I refresh my page or go to backward page then logout menu appears. Because after re-rendering value get in localstorage. Can you please help me out? I am stuck with it. Commented May 16, 2017 at 5:13
  • Possible duplicate of ReactJs React-Router Navigation/show and hide login logout menu Commented May 16, 2017 at 7:33

1 Answer 1

2

You should have some state management strategy behind the scene to implement this behavior. So, you can have the following component structure

App
- Nav
- LoginForm

Without any state management library like redux/mobX you need to have state defined in App component

class App extends Component {
  constructor(props) {
    super(props);
    this.onLoggedInChanged = this.onLoggedInChanged.bind(this);
    this.state = {
      isLoggedIn: false
    }
  }
  onLoggedInChanged(isLoggedIn) {
    this.setState({
      isLoggedIn: isLoggedIn
    });
  }
  render() {
    return (
      <Nav isLoggedIn={this.state.isLoggedIn} />
      <LoginForm onLoggedInChanged={this.onLoggedInChanged}></LoginForm>
    );
  }
}

Then in your Nav component you can use isLoggedIn flag

Nav = () => {
  let loginElement = this.props.isLoggedIn ? 'Logged in user' : 'Not logged in'
  return (<div>{loginElement }</div>)
}

You can find more information about state in react application in their docs here https://facebook.github.io/react-native/docs/state.html

In redux/mobx it will be done in a different way.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.