okaryo.log

Applying styles to custom elements with styled-components | okaryo.log

Applying styles to custom elements with styled-components

    #styled-components#React#CSS

Introduction

Usually, when using styled-components, I’ve only ever used it on basic HTML tags like styled.div or styled.p. I had never applied styles to custom components I made, so I wanted to leave a note for future reference.

Method

By allowing the component you want to style to accept a className prop, you can apply styles to custom components using the familiar styled method.

const MyComponent = ({ className }) => (<div className={className}>component</div>)

const StyledComponent = styled(MyComponent)`
  background-color: red;
  font-size: 24px;
`

Note that when using react-native, it seems you should use style instead of className.

Conclusion

The official documentation can be found below. This was written in the beginning sections of the Basics chapter. It’s always crucial to refer to the documentation.


Related Posts
Related Posts
Promotion

This site uses Google Analytics.