0

I am new to React and Gatsby and I want to condition a css rule based upon a value I am retrieving from my backend. This is my current frontend code:

{course.map(item => {
            return (
              <div key={item.id} className="job-desc">
                <h4>Kurs:</h4>
                <h4>{item.title}</h4>
                <span>{item.credits}&nbsp;poäng</span>
                <span>startdatum: {item.start}</span>&nbsp;
                <span>slutdatum: {item.end}</span>
              </div>
            )
          })}

What I would like to achieve is to set the class name for h4 tag from the current class job-desc h4 rule to .educationsOver if the date value in item.end is older then current date.

Instead of:

<h4>{item.title}</h4>

So maybe something like:

const current = new Date();

    <h4 className={`current.getDate() > ${item.end} ? "educationsOver" : "job-desc"`}>{item.title}</h4>

But this is the generated HTML code for the first occurrence of the map loop:

<h4 class="current.getDate() > 2021-02-05 ? "educationsOver" :"job-desc"">Kommunikation</h4>

2021-02-05 being the first value of {item.end}

What am I missing in my code?

1 Answer 1

1

Remove template literal string (backtick):

<h4 className={current.getDate() > item.end ? "educationsOver" : "job-desc"}>

Also, unwrapped item.end with ${} since it has no use of template literal string.

When you use template literal, you have to wrap with ${} - ${your_variable_or_expression}.

Your example could be written as:

{`${current.getDate() > item.end ? "educationsOver" : "job-desc"}`}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I tried out both of your suggestions. But there must be something wrong with my logic, in both cases the html output is with the .job-desc class, the . educationsOver class never kicks in even though I have a series of end dates that end before the current date. Is my variable "current" that holds the current date declared on the wrong place maybe or something wrong with my ternary logic? When I console log the variable current, I do get the current data back as many times as the length of the array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.