[SOLVED] Iterate through array of objects returning a React element, then returning a different element based on a max length?

Issue

This Content is from Stack Overflow. Question asked by BigBoyyo

I looked for duplicates to this question but couldn’t find anything specific enough. Please link me otherwise!

So I have an array of objects (in this case a User’s Game Characters).

I want a user to only be able to create a maximum of 3 characters (handled with a controller in the backend)

On the User’s Character Page I want to render Empty Character slots, max of 3, if no characters exist. If characters exist, then render those instead, replacing the empty slots.

Making a fetch request to update the characters state with a useEffect hook.

 const charFilled = characters.map((c, i) => {
    return <CharacterFilled char={c} idx={i} />;
  });

Have something like this above to map out the Used Character slots.

I am trying to figure out how to return the component for as many characters that exist, and then return the component for the remaining (up to 3 total) slots.

So for that I was trying something as follows:

  const maxThree = (chars, maxLength) => {
    for (let i = 0; i < chars.length; i++) {
      if (chars.length <= maxLength) {
        return <CharacterFilled char={chars[i]} idx={i} />;
      } else {
        return <CharacterSlot />;
      }
    }
  };

<div className="character-creation">{maxThree(characters, 3)}</div>

This is only returning a single character (which makes sense). I’m not properly iterating because of the if/else statement I believe.

Having a hard time wrapping my head around this scenario, any advice?



Solution

So this is what I ended up figuring out. Would love to see other solutions!

  const maxThree = (chars, maxLength) => {
    let result = [];
    let diff = maxLength - chars.length;
    for (let i = 0; i < chars.length; i++) {
      result.push(<CharacterFilled char={chars[i]} idx={i} key={i} />);
    }

    const createCharSlots = () => {
      let arr = [];
      for (let i = 0; i < diff; i++) {
        arr.push(<CharacterSlot key={uuidv4()} />);
      }
      return arr;
    };

    result = result.concat(createCharSlots());
    return result;
  };


This Question was asked in StackOverflow by BigBoyyo and Answered by BigBoyyo It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?