skip to Main Content

I have the below:

    <div className="grid md:grid-cols-2 sm:grid-cols-2 grid-cols-1 gap-16 mt-24 px-4">
      {status === "success" &&
        delve(data, "restaurants") &&
        data.restaurants.map((restaurant, index) => (
        <div className=""> <---------------- i.e.
          <RestaurantCard
            {...restaurant.attributes}
            locale={locale}
            key={index}
          />
        </div>
        ))}
    </div>

I want to apply a class to every other element within my .map function. Reason is, as opposed to standard side by side grid column, I am creating a checkerboard type layout, so every other item I will need to margin up higher. How could I apply such a style to only other item in data.restaurants.map((restaurant, index) => ( ?

4

Answers


  1. I hate this answer because this does not make sense to me.

    Login or Signup to reply.
  2. You can apply conditional className according to your index.

    For example,

        <div className="grid md:grid-cols-2 sm:grid-cols-2 grid-cols-1 gap-16 mt-24 px-4">
          {status === "success" &&
            delve(data, "restaurants") &&
            data.restaurants.map((restaurant, index) => (
            <div className={"" + (index % 2 ? 'odd' : 'even')}> <---------------- i.e.
              <RestaurantCard
                {...restaurant.attributes}
                locale={locale}
                key={index}
              />
            </div>
            ))}
        </div>
    
    
    Login or Signup to reply.
  3. If is the same style, add your class in the div inside of the map

            <div className="YOURCLASS"> <---------------- i.e.
    

    Also if you need to make some logic to apply the class

            <div className={variable === 'something' ? CLASS1 : CLASS2}> <---------------- i.e.
    

    Also you can apply the class to your component

    <RestaurantCard
     {...restaurant.attributes}
     locale={locale}
     key={index}
     style={styles...}
    />
    

    And then apply that style in the component file

    Login or Signup to reply.
  4. You can use the modulus operator (%) to check if the index is even or odd. Based on that, you can conditionally apply different classes to alternate elements, creating a pattern or checker switching logic.

    Based on your example:

    <div className="grid md:grid-cols-2 sm:grid-cols-2 grid-cols-1 gap-16 mt-24 px-4">
      {status === "success" &&
        delve(data, "restaurants") &&
        data.restaurants.map((restaurant, index) => (
          <div className={index % 2 === 0 ? "even-item" : "odd-item"}>
            <RestaurantCard {...restaurant.attributes} locale={locale} key={index} />
          </div>
        ))}
    </div>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search