Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

196
Views
ReactJs conditional rendering not working

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>
    );
  }
}
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

0

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>
    );
  }
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!