Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

192
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda