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

277
Vistas
How to conditionally add or not onClick on a div in react?

I would like to know if it is possible to set onClick on a div element in react based on the value of a property in my case canClick.

I am aware that I can check this.state directly in handler instead I am looking for a solution to be implemented inside render.

...
handler(){
}

render() {
  const { canClick} = this.state
  return (
    <div onClick={this.handler}>hello</div>
  )
}
...
over 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

Put the condition like this:

onClick={canClick ? this.handler : undefined }

Working Code:

class App extends React.Component {
  
   _click(){
      // it will not print the value
      console.log('yes');
   }

   render(){
      return (
        <div>
          <div onClick={false ? this._click : undefined }>Click</div>
        </div>
      )
   }
}

ReactDOM.render(<App />, document.body);
<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>

over 4 years ago · Santiago Trujillo Denunciar

0

You can treat the elements attributes (like onClick) as object properties. Use the spread operator to only on condition, spread the onClick:

<div
  {...(canClick && { onClick: this.handler })}
>
  hello
</div>
over 4 years ago · Santiago Trujillo Denunciar

0

<div onClick={canClick ? this.handler : undefined} />

If you opt for a different falsy value instead of undefined in this ternary (i.e. false or null) React (currently) throws the following warning:

"If you used to conditionally omit it with onClick={condition && value}, pass onClick={condition ? value : undefined} instead."

Edit 2020-01-05: only false throws the above error (React source code here).

over 4 years ago · Santiago Trujillo 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