Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    classSet has been deprecated

    Applying conditional styles in React with classSet add-on


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



    Become a Member to view code

    You must be a Pro Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    orLog In




    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.