i am create an array in react to print images select only images i want based on to numbers

Viewed 23

i am running into a tricky problem, i am creating an array of 100 elements, and mapping through it an generating an image for each :

{Array.from({ length: 100 }).map((_, i) => (
      <>
        <img
          key={i}
          className={`h-12 object-contain cursor-pointer `}
          src="/images/panneau.png"
          alt=""
        />
      </>
))}

here is what i get: enter image description here what i want :

  • for example i have tow numbers 5 and 6 i want to add opacity-50 to this images in the range of 6 * 5 : enter image description here
1 Answers

The problem you are tying to solve is converting a flat array index to a 2 dimentional array indexes, then you can use those to apply conditional code.

Let's say you want to have 10 images for each row, I am calling this WIDTH.

you can get the current row index with the formula: y = Math.floor(i / WIDTH); and you can get the current index in each row with: x = i % WIDTH;

now that you have those you can do something like:

function MyComponent() {
    const WIDTH = 10; //number of images in one row
    return <>
        {Array.from({ length: 100 }).map((_, i) => {
            x = Math.floor(i / WIDTH);
            y = i % WIDTH;
            opacity = (x <= 5) && (y <= 4) ? ' opacity-50' : '';
            return (
                <img key={i}
                    className={`h-12 object-contain cursor-pointer` + opacity}
                    src="/images/panneau.png"
                    alt=""
                />
            );
        })}
    </>
}

Related