BACK TO HOME

Understanding the styled-components CSS prop

Published on Sat Aug 22 2020

The CSS prop is one of the most powerful features of styled-components. It allows us to add styling to basically any component without manually creating a styled() version of it. Let's talk about it!

Using the CSS Prop

To create a styled-component, we need to create a StyledParagraph component before we can actually use it. And once the component is created, styles will be injected into the page on mount.

import styled from 'styled-components'
  
const StyledParagraph = styled.p`
  color: dodgerblue;
  padding: 1rem;
`
//usage
<StyledParagraph>Hello!</StyledParagraph>

It's easier with the CSS prop

The CSS prop makes everything ridiculuously easy. This is how we can style a paragraph element with the CSS prop. Instead of importing styled from styled-components we import styled-components/macro and then add our css rules into the css prop like so.

import 'styled-components/macro'
//usage
<p css={`
  color:dodgerblue;
  padding: 1rem;`} 
>
  Hello!
</p>  

The CSS prop is a compile time babel helper. It converts

import 'styled-components/macro'

<element css={`rules`}> 

to

import styled from 'styled-components'

const StyledElement = styled("element")`
  rules
`

It also works with components, as long as the components are either styled components or third party components which forward className down to underlying elements.

import 'styled-components/macro'

function GoodComponent({className, children}){
  return <p className={className}>{children}</p>
}

//usage
<GoodComponent css={`
  color:dodgerblue;
  padding: 1rem;
`}>
  Hello!
</GoodComponent>

The CSS Prop is an awesome addition to styled-components and helps us write styled components much quicker. I am sure you will love using it in your projects!

Sign up to my newsletter

Get latest news and tips in Fullstack web development right into your inbox!

No spam. I promise!

© 2020 Bhargav Ponnapalli. All rights reserved.