0

I have react component the loop through data. I need to check add ClassName dynamically based on one of the field '{stateItem.transactionCoverStatus}' value.

Let's say if transactionCoverStatus == x then color-blue else if == y then color-red.. and so on.

There are about 5 possible values so also wonder if I can calculate in separate method which takes parameter and return class name!

  <tbody>
      {
         eziTransactionCollection.map((stateItem, stateIndex) =>(

           <tr key={stateIndex}>
              <td className="td-align-centre">{stateItem.eziTransactionId}</td>
              <td>{stateItem.transactionCoverStatus}</td>
              <td>{stateItem.loginDateTime}</td>
              <td>{stateItem.logoutDateTime}</td>
            </tr>
         )) 

2 Answers 2

1

You could use an object to map the class variants and pass your status to retrieve the value:

const COVER_COLORS = {
  active: 'blue',
  disabled: 'gray',
  warning: 'yellow',
}

const coverClass = (coverStatus) => {
  const variant = COVER_COLORS[coverStatus]
  return variant ? `color-${variant}` : '' // or return a default class
}

...

           <tr key={stateIndex}>
              <td className="td-align-centre">{stateItem.eziTransactionId}</td>
              <td className={coverClass(stateItem.transactionCoverStatus)}>{stateItem.transactionCoverStatus}</td>
              <td>{stateItem.loginDateTime}</td>
              <td>{stateItem.logoutDateTime}</td>
            </tr>
Sign up to request clarification or add additional context in comments.

Comments

1

It is quite easy to give a condition on classname in react

: means else.

? means then.

 <td className={stateItem.transactionCoverStatus==='x' ? 'blue' : 'red'}>{stateItem.transactionCoverStatus}</td>

If you want to give multiple conditions. You should use || operator

<td className={stateItem.transactionCoverStatus==='x' || stateItem.transactionCoverStatus==='y'  ?  'red' : 'green'}>{stateItem.transactionCoverStatus}</td>

Comments

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.