Home > Software engineering >  ReactJs conditional rendering not working
ReactJs conditional rendering not working

Time:11-08

I am trying to call the onLogin() function from a child called Login. This function will set the state based on which the conditional rendering is done.

The problem is that Home is not getting rendered after setState is called. In fact the function getView() is not getting called after calling setState(), although the view is updated after i refresh the page.

class App extends React.Component {
  constructor(props) {
    super(props);
    this.onLogin.bind(this);
    this.state = {userLoggedIn: !!localStorage.getItem(USER_NAME)};
  }

  onLogin() {
    this.setState({userLoggedIn: true});
  }

  getView() {
    return this.state.userLoggedIn ? <Home /> :  <Login onLogin={this.onLogin} />;
  }

  render() {
    return (
        <span>
          {this.getView()}
        </span>
    );
  }
}

CodePudding user response:

You need to add .bind(this) where you pass the prop to Login component like this:

<Login onLogin={this.onLogin.bind(this)} />

and you can delete the line after super(props); Here is a link to codesandbox: https://codesandbox.io/s/boring-chaum-5l8k6?file=/src/App.js

CodePudding user response:

You don't seem to have bound getView method like you did for onLogin. To avoid binding issues maybe just use arrow functions like so

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {userLoggedIn: !!localStorage.getItem(USER_NAME)};
  }

  const onLogin = () => {
    this.setState({userLoggedIn: true});
  }

  const getView = () => {
    return this.state.userLoggedIn ? <Home /> :  <Login onLogin={this.onLogin} />;
  }

  render() {
    return (
        <span>
          {this.getView()}
        </span>
    );
  }
}
  • Related