Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson

Already subscribed? Sign In

Autoplay

    Styling React Components With Aphrodite

    Jamison DanceJamison Dance

    Aphrodite is a library styling React components.

    You get all the benefits of inline styles (encapsulation, no build step, no CSS cascade, building up styling with JavaScript instead of a preprocessor language) with all the benefits of CSS (animations and transitions, pseudo-classes, media queries).

    Learn how to use Aphrodite to style reusable React components.

    reactReact
    aphroditeAphrodite
    cssCSS
    Code

    Code

    Become a Member to view code

    You must be a 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
    Transcript

    Transcript

    00:00 Here's a simple react button component that we can click on. It's pretty ugly. Let's add some inline styles by creating this style object, and then we'll pass it in as style on our button. Now it's prettier, and it still works the same. Also because we're defining inline styles, they come along for free when anyone uses this component.

    00:29 Now let's add in Aphrodite by importing StyleSheet and css from the aphrodite package. We take our styles object and wrap it in a call, so StyleSheet.create. We also add one level nesting to our styles object. Call everything button. Instead of assigning things to style, we'll use className.

    01:02 We call our css function (styles.button). When we save, everything looks the exact same. If we inspect our element though, we notice that now we have a class instead of inline styles. Also if we look up in the head we see this data-aphrodite style tag, which contains styles that look suspiciously like what we defined here.

    01:32 That's because when you call css and pass in a StyleSheet object, Aphrodite is parsing this code, turning it into css, and injecting it into the DOM. It also uses the object key to generate a unique class name, that it then shares and passes in as the className attribute.

    01:54 Let's use css we already know, to add an active and a hover state to this button. We first define an active pseudo class, to add a boxShadow when someone's clicking on the button. It's beautiful. Next we'll add a hover pseudo class, so that when someone hovers on the button it turns colors.

    02:14 Our button is a little easier to interact with now, and we get all the benefits of css like pseudo classes, along with the benefits of inline styles like encapsulation and avoiding selector wars and specificity problems.

    Discuss

    Discuss