Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple CSS conditional classes using React

Tags:

css

reactjs

I want to incorporate 3 more conditional classes into this...

<li className={`list-group-item ${todo.completed ? " strike-through" : ""}`}

I now want ${todo.priority} to be included/alongside with this, which will assign classes:

"alert alert-info", "alert alert-warning", and "alert alert-danger" based on corresponding values in a drop down: 1, 2, 3.

Can someone help me with this, thank you in advance!

like image 962
sWarren Avatar asked Oct 31 '18 21:10

sWarren


2 Answers

Others have already provided some more "flexible" solutions, so I'll just add the quick and dirty one:

<li className={`list-group-item ${todo.completed ? " strike-through" : ""} ${todo.priority === 1 ? "alert alert-info" : (todo.priority === 2 ? "alert alert-warning" : "alert alert-danger")}`} />

For readability's sake:

const completed = todo.completed ? " strike-through" : "";
const priority = todo.priority === 1 ? "alert alert-info" : (todo.priority === 2 ? "alert alert-warning" : "alert alert-danger");
...
<li className={`list-group-item ${completed} ${priority}`} />
like image 195
Chris Avatar answered Sep 28 '22 02:09

Chris


I recommend the classnames package. It's a widely-used package and serves a straightforward purpose. Any key whose value is truthy will make it into the final class name:

import cx from 'classnames';

<li className={cx('list-group-item', {
   'alert alert-danger': value === 3,
   'alert alert-info': value === 1,
   'alert alert-warning': value === 2,
   'strike-through': todo.completed,
})} />
like image 22
Ross Allen Avatar answered Sep 28 '22 00:09

Ross Allen