1×
Become a member
to unlock all features

Level Up!

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

Autoplay

    Use Styled Components with the Object syntax

    Sara VieiraSara Vieira
    reactReact

    In this lesson, we will learn how to use the styled-components library using the object notation instead of template strings.

    We will go through a heading and transform it from template literals to objects

    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
    Discuss

    Discuss

    Transcript

    Transcript

    Sara Vieira: 0:00 We have two styled components here. There's two headings, this one is bigger than this one and we can define it here with the props. We're doing this with backticks. We're doing this basically text style.

    0:12 There is also another way that we can style these components. We can use object-based styling. Let's see how different that is.

    0:19 I'm going to first comment this, so, add line comments, and right now, we're going to get an error. Heading is not defined. I'm going to say const heading = styled and it's the same thing, so style.h1. Then, instead of opening backticks, you open function and this function can return an object.

    0:37 Let's start with textAlign and I'm going to say center with quotes and all objects is in the center. Right now here, we do get the prop. Another thing that this can return is a function and that function takes in the props. For that, we need to say props here and then do this and this.

    0:57 Now we have access to the props here. All the thing that we want is small, so let me just deconstruct small from here, so do this. Add small, and now we can say fontSize, and I'm going to say, if small, then do 16, else do 24. I'm missing one here, and there you go.

    1:19 It is slightly cleaner, and there's no need for pixels, so both things work. If I do 24 pixels, that will also work. In Object, it will always default to pixels, so if you want to do something else, like Ems or something, you will have to type it, but it will default to pixels.

    1:37 Now, so that I don't forget, here's a comma, and then we add the next one. I'm going to say fontSize. Now fontSize, fontFamily. I'm going to copy it from here, so apple-system, sans-serif.

    1:50 Let's add the quotes and copy apple-system, sans-serif, and we can delete this.

    1:56 Both of these things...Let me bring it back. Both of these things -- this and this -- do exactly the same thing. They're just different ways of writing it, so whatever you prefer can be the way you write styled-components.