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

154
Vistas
How do I conditionally render a tailwind class in react?

I am creating a website that uses Tailwind(3.0.2) and ReactJs (17.0.2).

I have a div that wraps a navbar I would like to render conditionally depending on screen size. This code works as the base case:

<div className= { (showIcon ? "left-0" : `-left-full`) + " fixed bottom-0 top-12 bg-gray-500 bg-opacity-60 w-10/12 text-white p-2 flex flex-col"} >

For medium screens and larger (md: in tailwind), I have prepared this code which also works on its own :

<div className= {nav ? 'nav active' : 'nav'}  > // (Nav and nav active are states defined elsewhere)

I want to combine both snippets but my code throws compiler errors. For example:

<div className= { (showIcon ? "left-0" : `-left-full`) + " fixed bottom-0 top-12 bg-gray-500 bg-opacity-60 w-10/12 text-white p-2 flex flex-col"} md:{nav ? 'nav active' : 'nav'} >

 Line 40:151:  Parsing error: Unexpected token (40:151)
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

I hope this is what you need:

<div className={`
    fixed bottom-0 top-12 bg-gray-500 bg-opacity-60 
    w-10/12 text-white p-2 flex flex-col

    ${showIcon?"left-0":"-left-full"}

    md:${nav ? 'nav active' : 'nav'}
    `}>

    </div>
about 4 years ago · Juan Pablo Isaza Denunciar

0

Using tailwind I often write utils classnames function to divide class into groups according to their type for more readable

const classnames = (...classes: string[]) => classes.join(` `);

<div className={classnames(
    `${showIcon ? "left-0" : "-left-full"}`,
    "fixed bottom-0 top-12",
    "bg-gray-500 bg-opacity-60",
    "w-10/12",
    "text-white",
    "p-2",
    "flex flex-col",
    "nav",
  )}
>

If you want to use directive with custom class you might need to use screen()

@media screen(sm) {
  .your-class {
    @apply ...your-tailwind-classess
  }
}

@media screen(md) {
  /* ... */
}
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