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 the `attrs` method to add HTML attributes in styled-components

    Sara VieiraSara Vieira
    reactReact

    In this lesson, we will learn about the attrs method that allows us to change and add attributes to our styled elements.

    We will use to add some defaults for the type of a button.

    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: I have these two buttons here and these two buttons as you can see have no type assigned to them. It's always good for buttons to have at least a type of button and for accessibility purposes and also for readability in terms of the DOM.

    It's hard for us to remember this as developers sometimes. That's why I want to talk about attrs, which are a chainable method that exists in styled-components that allows you to push attributes into your actual HTML element.

    Using that, we can actually "fix these buttons". Let me add attrs here. This can return an object or a function. In this case, I'm just going to return an object and I'm going to say that the type is now going to be equal to button. By default, all of the buttons will have a type of button.

    We do have a problem though, which is that if this one for example is supposed to have a type of submit, it will never get overwritten, because it gets here and it's like, "Oh, OK, you're one type of button." Whatever it is here actually overrides what is said here, which is not good.

    Let's do this in a way that this can actually get to props. As I said, this can also return a function. I can say props, and then do this, close it here and here, and now the props are passed into here. I can say props.type, or it is a button.

    In this case, you can see that we have a type of submit, which is the one that I added, and then we have a type of button. This is how you can change the attributes of an HTML element using styled-components.