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

190
Vistas
Add a child `div` component on button click (ReactJS)

I am trying to add a child div component (div-col inside of div-row) on the click of the button. Like here I am trying to change the orientation of the cards from the grid to list view. I am using the bootstrap inbuilt class here.

If it is grid view, then

<div className="row">
  {notes.map((item, key) => {
    return <Noteitem  />;
  })}
</div>

if the listview button is clicked

<div className="row">
  <div className="col"> 
    {notes.map((item, key) => {
      return <Noteitem  />;
    })}
  </div> 
</div> 

Do I need to use return the DOM for both separately?? Or welcome for any other approach also.

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

create state myView and set default to 'GridView' listView button is clicked, setState to 'ListView'.

use this state, render like

{
  myView === "GridView" ? (
    <div className="row">
        {notes.map((item, key) => {
          return <Noteitem />;
        })}
    </div>
  ) : (
    <div className="row">
      <div className="col">
        {notes.map((item, key) => {
          return <Noteitem />;
        })}
      </div>
    </div>
  );
}


about 4 years ago · Juan Pablo Isaza Denunciar

0

Similar to @Bee answer, but a bit more succinct and fleshed out:

const [grid, setGrid] = useState(false)

return (
    <button onClick={() => setGrid(!grid)} />
    <div className="row">
       <div className={grid ? "col" : ""}> 
         {notes.map((item, key) => {
            return <Noteitem  />;
         })}
      </div> 
    </div>
)

Explanation

You keep the div element on the DOM and just change the className to and from col or nullish. Use the onClick attribute on your button to toggle the grid view on and off. Keep the state value as a Boolean so that you can reference its truthy/falsey value directly using a ternary operator to assign the className value to the div.

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