Applying conditional styles in React with classSet add-on

Joe Maddalone
InstructorJoe Maddalone
Share this video with your friends

Social Share Links

Send Tweet
Published 9 years ago
Updated 5 years ago

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

[00:00] 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.

[00:09] 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.

[00:25] 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.

[00:41] 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.

[01:07] 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".

[01:26] 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.

[01:40] 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.

Esteban Martini
Esteban Martini
~ 8 years ago

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

Markdown supported.
Become a member to join the discussionEnroll Today