Home > Back-end >  How to add a child `div` componen on button click in reactJS?
How to add a child `div` componen on button click in reactJS?

Time:10-24

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.

CodePudding user response:

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>
  );
}


CodePudding user response:

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.

  • Related