Home > Net >  For Loops and React JS
For Loops and React JS

Time:12-10

So I have this function here:

 const printCardList = (arr) => {
    const uo_list = document.getElementById("verify_list");
    arr.forEach((card) => {
      let list_item = document.createElement("LI");
      let str = card.name   " "   card.mana_cost   " "   card.set_name;    
      list_item.appendChild(document.createTextNode(str));
      uo_list.appendChild(list_item);
    });
  };

and its suppose to insert list items into and unorder list from an array of card objects.

return(
<div className="list-confirm">
        <h3> Please confirm card list </h3>
        <ul id="verify_list"></ul>
        <br />
        <button onClick={getCardList}>Confirm</button>
      </div>
);

If I do a console.log on arr I can verify that it is an array of cards, but if I console.log card from inside the for each it does not even trigger. It's like the for each does not run. Does anyone have an idea why this is happening?

CodePudding user response:

You should change the onclick, more precisly call the method after betting items from getCardList() method.

This is an example:

const printCardList = (arr) => {
   const uo_list = document.getElementById("verify_list");
   arr.forEach((card) => {
      let list_item = document.createElement("li");
      let str = card.name   " "   card.mana_cost   " "   card.set_name;    
      list_item.appendChild(document.createTextNode(str));
      uo_list.appendChild(list_item);
   });
};

// this is a test method. Not the real one
const getCardList = () => {
   return [ { name: "Card", mana_cost: 0, set_name: "Set: Card" } ];
};
<div className="list-confirm">
    <h3> Please confirm card list </h3>
    <ul id="verify_list"></ul>
    <br />
    <button onClick="printCardList(getCardList())">Confirm</button>
</div>

CodePudding user response:

I'm not sure what you are trying to do, the first part of your code is plain javascript that manipulates the DOM, while the second part is react js object. You normally don't want to mix these two, either you code your javascript as part of the html, like the first part, or - if you want to create an array of cards in react you can do something like:

let cardList = arr.map(card => {
    listItem = <li>{card.name   " "   card.mana_cost   " "   card.set_name }</li>    
    return listItem;
})

return(
<div className="list-confirm">
    <h3> Please confirm card list </h3>
    <ul id="verify_list">{cardList}</ul>
    <br />
    <button onClick={getCardList}>Confirm</button>
  </div>
);

what I did is assigned the list itself to a variable named 'cardList', JSX object are just javascript objects, so you can assign them to a variable or return then from a function. to place the card list inside the page (or component), you can just use the {} notation, which will embed the cardList object as part of the returned JSX object.

  • Related