2

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)

xgarb
  • 159
  • 2
  • 9

2 Answers2

2

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.

tsflorus
  • 31
  • 2
  • This didn't work for me. Possibly because I'm using a global stylesheet and React needs to see the class name defined at the top of the document matched in the className declaration in the return to render it correctly. With your code I got:
    when it needs to be:
    – xgarb Jun 10 '21 at 13:41
  • Well in that case I don't understand what you want to do... I was thinking that you wanted to have a className equal to clubNightsIconMonday. But anyway, the logic stands. If you want to concatenate a string with a variable for a className, you have to make sure that the variable is in parenthesis. Let me know what result you need, I'm a little bit curious. Thomas. – tsflorus Jun 11 '21 at 12:03
  • I want the className to be clubNightsIconMonday and the code you provided does that but React doesn't render it to --club-nights-icon-monday-- in the final HTML and so it doesn't display with the correct CSS. I'm importing the CSS like this: import { clubNightsIconMonday, } from "../components/layout.module.css"; I think its just the way React (or maybe Gatsby) expects things to be. – xgarb Jun 11 '21 at 15:16
0

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>
xgarb
  • 159
  • 2
  • 9