Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

198
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda