Home > OS >  Return x-amount of divs depending on list size
Return x-amount of divs depending on list size

Time:09-24

I have a component that roughly looks something like this:

import cx from 'clsx';

const myComponent = () => {
  function myFunc(binaryList) {
    for (const binaryVal of binaryList) {
      if (binaryVal == 1) {
        return <div className={cx(styles.all, styles.special)}></div>;
      } else if (binaryVal == 0) {
        return <div className={cx(styles.all)}></div>;
      }
    }
  }

  return (
    <div className={styles.wrapper}>
      <div className={styles.listClass}>{myFunc(myBinaryList)}</div>
    </div>
  );
};

export default myComponent;

Basically, I get a list (myBinaryList) from somewhere, which I input into the function myFunc. This list can have different lengths, but consists of 1's and 0's, so something like:

myBinaryList = [0, 0, 1, 1, 1, 0, 0, 1]

What I would like to do is do take this list myBinaryList, use it in the function myFunc, and then it should output the same number of divs as the length of the list. So basically the output of this list should be:

<div className={cx(styles.all)}></div>
<div className={cx(styles.all)}></div>
<div className={cx(styles.all, styles.special)}></div>
<div className={cx(styles.all, styles.special)}></div>
<div className={cx(styles.all, styles.special)}></div>
<div className={cx(styles.all)}></div>
<div className={cx(styles.all)}></div>
<div className={cx(styles.all, styles.special)}></div>

But right now I only get one div as output. What am I doing wrong?

CodePudding user response:

You need to return an array of divs. Now your myFunc function is returning only a div. Try doing it with map.

 function myFunc(binaryList) {
   return binaryList.map(binaryVal => {
     if (binaryVal == 1) {
       return <div className={cx(styles.all, styles.special)}></div>
     } else if (binaryVal == 0) {
       return <div className={cx(styles.all)}></div>
     }
   });
 }
  • Related