DEV Community

Cover image for styled-components
Samantha Frangi
Samantha Frangi

Posted on

styled-components

A couple nights ago, I was working on a project that I'm building in React.

Making sure I'm referencing class names correctly and importing CSS files in the right places was something I've done before. This time, none of my styles were applying and I'd done all the troubleshooting I could. So I hit up Google and look up "styling in React". Very broad search terms, I know, but it helped me find styled-components.

What is styled-components?

In short, styled-components allow you to write CSS in JS files.

I'd never used styled-components before, and I only remembered hearing about it very briefly.

First, I had to install the styled-components package. To do so I ran:

npm i styled-components

Then, I got to work on my Footer.js file.

The Footer component came out like this:

import { Link } from 'react-router-dom'
import styled from 'styled-components'

const SiteFooter = styled.footer `
  position: fixed;
  background-color: #8FBB99;
  bottom: 0;
  width: 100%;
`

const linkStyle = {
  margin: "1rem",
  textDecoration: "none",
  color: "white",
}


function Footer() {
  return (
    <SiteFooter>
      <Link to="/contact" style={linkStyle}>
        Contact
      </Link>
    </SiteFooter>
  )
}

export default Footer;
Enter fullscreen mode Exit fullscreen mode

And voila! We have a footer 🎉

Very basic footer

By importing styled from the styled-components package, I am able to create a React component that will render the selected HTML element.

Let's say I wanted to make a div that is a red square. Styled-components allows me to reference the red square as a component that I might name ... RedSquare.

const RedSquare = styled.div`
    width: 100px;
    height: 100px;
    background-color: red;
`
Enter fullscreen mode Exit fullscreen mode

In SiteFooter, you'll notice that the CSS is written inside of back ticks - these are tagged template literals. An easy way to think of tagged template literals is like a function.

Benefits of using styled-components

A footer was a great reason for using styled-components because it requires minimal styling.

Since I've handled all the styling in the component itself, I don't have to search through files for the class-name and make changes. Styling, markup, and logic are all in one file and makes for a smooth developer experience.

This has been quite the unlock in my deep dive into React!

What are your favorite things about React?

Top comments (9)

Collapse
 
joelbonetr profile image
JoelBonetR 🥇 • Edited

I'm in love with styled-components.
I feel it the best improvement of the last years in style management related to webapps with SPA architecture.

You can also pass props into a styled-component, which makes it more powerful, see below:

export const MyComponent = styled.div`
  background-color: ${(props) => (props.backgroundColor)}
`;

<MyComponent backgroundColor={'#f5f5f5'}>
// content
<MyComponent />
<MyComponent backgroundColor={'#333'}>
// content
<MyComponent />
Enter fullscreen mode Exit fullscreen mode

So you'll get the first one in almost white and the second one in almost black.

Another example:

export const ValueLine = styled.div`
  background: linear-gradient(
    90deg,
    rgba(134, 189, 136, 1) 0%,
    rgba(134, 189, 136, 1) ${(props) => props.percent}%,
    rgba(193, 28, 64, 1) ${(props) => props.percent}%,
    rgba(193, 28, 64, 1) 100%
  );
`;

<ValueLine percent={getPercentile(myApiResponseData)} />
Enter fullscreen mode Exit fullscreen mode

As result you can easily get a dynamic background based on some property that you got from a service or whatever:

linear dynamic percentile background

Isn't it convenient? 😁

Collapse
 
samanthaelainef profile image
Samantha Frangi

Wow! Thanks for sharing I'm going to play around with that for sure! 😊

Collapse
 
link2twenty profile image
Andrew Bone

I used to use styled-components but it makes your JavaScript files larger and thus your loading slower. I now use scss and css modules.

This method splits styles out into a separate css file speeding up page loading.

Collapse
 
samanthaelainef profile image
Samantha Frangi

Thanks for sharing this example. This looks familiar and I think I have used it before in a class, I will definitely be testing it out!

Collapse
 
mrcaidev profile image
Yuwang Cai

I love styled component too. But I'm worrying about its performance, especially after reading this post and realizing I might have probably used it in the wrong way. I'm still using Tailwind now.

Collapse
 
joelbonetr profile image
JoelBonetR 🥇

Hi @mrcaidev , why are you worried about performance?

I checked the entire post you linked and it is all true and also nice to have.

Collapse
 
mrcaidev profile image
Yuwang Cai • Edited

I remember when I read this post a few months ago, it mentioned that: If we pass some props to a styled component, then every time these props change, the CSS in the HTML's <head> will be cleared and injected again, leading to some performance issues.And the author provided some methods to optimize it. But just now I read it through again and can't find these lines. Maybe situations changed and the post has been modified accordingly.
I do think CSS-in-JS solutions will inevitably be slower than static CSS. But I'm not saying they are bad - instead I love them. The flexibility they bring about is tremendous.

Thread Thread
 
joelbonetr profile image
JoelBonetR 🥇

Oh, maybe the author checked in more detail what styled-components do behind the scenes or provided a better test environment for its tests. It may be a issue related to another lib instead 🤷🏼‍♂️

Even that, the question would be "Why and when those props may change". I mean, if you declare a button with some props, it will look the same on every instantiation. This applies to almost anything we can use in our daily work.

On the other hand you can deal with real time thingy, that will add the need to update the data and, depending on the use-case, the props as well, in which case, the addition of those styles in this process is not something critical in performance terms. I tried it extensively before using it as building block at the beginning of a big project and it was maybe the best go to, better usually than Sass/SCSS modules and IMHO better than tailwind (I may write a post about that in a future).

Thread Thread
 
mrcaidev profile image
Yuwang Cai

Agree!