xgarb
xgarb

Reputation: 191

Concatenate className values in React map loop

I'm looping through the days of the week from a database query something like this where 'node.club_night_day' is one day of the week:

{nights.edges.map(({ node }, index) => (
  <div key={index}>
    <div className={clubNightsIcon+node.club_night_day}>
      <div>{node.club_night_name}</div>
    </div>
  </div>
))}

CSS:

.club-nights-icon-wednesday {
  background: linear-gradient(180deg, #DE9FAE 0%, #E70F50 100%);
}

I want the definition for the class to be

clubNightsIconMonday

clubNightsIconTuesday

Is this possible in React? (I'm working with GatsbyJS)

Upvotes: 2

Views: 1461

Answers (2)

xgarb
xgarb

Reputation: 191

After trying various ways to concatenate a string with the node value I decided to try a switch and after seeing this post: https://stackoverflow.com/a/51432223/2030399 I have this which works nicely...

              <div
                className={
                  {
                    Monday: clubNightsIconMonday,
                    Tuesday: clubNightsIconTuesday,
                    Wednesday: clubNightsIconWednesday,
                    Thursday: clubNightsIconThursday,
                    Friday: clubNightsIconFriday,
                    Saturday: clubNightsIconSaturday,
                    Sunday: clubNightsIconSunday,
                  }[node.club_night_day]
                }
              ></div>

Upvotes: 0

tsflorus
tsflorus

Reputation: 31

I've understand that "clubNightsIcon" isn't a variable but a string you want to pass. If this is the case then you should be able to do this:

<div className={"clubNightsIcon" + (node.club_night_day)}>

Thomas.

Upvotes: 2

Related Questions