This lesson is for PRO members.

Unlock this lesson NOW!
Already subscribed? sign in

Applying conditional styles in React with classSet add-on

2:17 React lesson by

Applying conditional classes can be a real chore in any framework. Luckily for us, React makes it easy with the classSet add-on.

Get the Code Now
click to level up

egghead.io comment guidelines

Avatar
egghead.io

Applying conditional classes can be a real chore in any framework. Luckily for us, React makes it easy with the classSet add-on.

Avatar
Esteban Martini

According to the React docs, classSet was deprectated in favor of classnames.

There is a Egghead.io lesson about it: Using the classnames library for conditional CSS in React. Would be cool remove this lesson or add a message pointing out about the new lesson

Apply conditional classes in JavaScript can prove to be a real pain, let alone implying multiple conditional classes, regardless of the framework that you're using.

Luckily, react makes this really easy for us, with an add-on called 'Class Set". For example, we've got a list of tasks. Each one has an importance, from zero to two, and a status being either a zero or a one, indicating whether or not that task has been completed.

We're just outputting all those into an unordered list, which you can see here, on the right. What we want to do is apply that class here, in the class name of the LI. We've got some really basic CSS for high, medium and low, indicating the importance.

Then we've got "complete", whether or not it's been completed. Right here, in our mapping, we are going to say, "verclasses=react.addons.classset". That's going to take in an object. The way this works is the key is the class that we want to apply. If its value evaluates to true, then it will apply that class.

The first one is "task". We obviously need that one here. What we're going to do is override this and just say "classes", right there in the class name. Let's go and do the status one. That's just going to be complete. What we want to do here is say "task.status=1".

If it equals one, we want to apply the complete class to it. We can load this up again and we can see that we get this little strike-through there. Awesome. Let's go and do the rest of them.

This one will be "high," and that's importance, "equals two", "medium importance equals one" and "low importance equals zero". It's going to load that up here. We can see we've got our blue, for medium, for class set, high is red, our medium is blue and our low is green. If we go ahead and change this one to "complete" and the importance on this one to "two", and load that up, we can see that our classes are, in fact, being applied.

HEY, QUICK QUESTION!
Joel's Head
Why are we asking?