Skip to content
Advertisement

For Loops and React JS

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?

Advertisement

Answer

Thanks for all the advice. In hindsight, I should have stuck to what I was learning and not try to freestyle. React is about using states. So rather than having a function that will generate HTML from an array of data and I had to do use “the state”. Then code the render to loop through the list of cards when the button is pressed.

const [state, setState] = useState([]);
const card_list= ()=> {...}
const changeState = ()=> {setState(card_list)}

return(
<div className="list-confirm">
    <h3> Please confirm card list </h3>
      <ul>
          {state.map((card) => (
            <li>{card.name}</li>
          ))}
        </ul>
    <br />
    <button onClick={changeSate}>Confirm</button>
  </div>
);
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement