DEV Community

Cover image for Introduction to styled-components
David Asaolu
David Asaolu

Posted on

Introduction to styled-components

Yes, I have always been like you, I've been styling my html elements in my React apps using classNames, because, that was the only available way in React.πŸ˜’

After completing a project, going back to maintain or edit the recently completed project is always stressful☹️.

I was also introduced to BEM syntax. BEM was quite helpful, but it wasn't still the best for me with React. Problem Unsolved! πŸ˜“

Not until few weeks ago, I was watching a tutorial video and I came across styled components. Sounds cool, but what is it all about?
Is it going to solve my problem? Is it less stressful?
Let's find out! 😊

Curious about Styled Components

So what exactly is styled-components?

According to the official website, styled components is the result of wondering how we could enhance CSS for styling React component systems. It uses the best bits of ES6 and CSS to style your apps without STRESS.πŸŽ‰

So how can you use styled-components in your React apps.

Install it via NPM

npm install --save styled-components
Enter fullscreen mode Exit fullscreen mode

Once, it is installed that's all.πŸŽ‰

Let's build this simple design using styled-components

styled-components example

In order to use styled-components in your react app, you will have to import styled-components, like this

import styled from "styled-components"
Enter fullscreen mode Exit fullscreen mode

Now, for the example above here is how the component looks like

import React from "react"
import styled from "styled-components" //The styled import


//In styled-components, every element is declared as a variable 

//and you are free to use any variable name you like.

//styled.main: main represents the html tag <main></main> that's 

//what Container is representing

const Container = styled.main` 
  width: 90%;
  background-color: #fff;
  padding: 30px;
  border-radius: 15px
`

//Header represents the h2 tag
const Header = styled.h2`
color: #192041;
font-weight: 700;
margin-bottom: 15px;
font-family: "Merriweather", serif;
`

//Form represents the form tag
const Form = styled.form`
width: 100%;
margin: 15px 0px;
display: flex;
align-items: center
` 

//InputContainer represents the input tag
const InputContainer = styled.input`
flex: 0.8;
margin-right: 10px;
height: 35px;
background-color: #e6e9fb;
border: 1px solid #ddd;
outline: none;
padding: 15px
`
//SubHeader represents the p-tag 
const SubHeader = styled.p`
  color: #000;
  font-weight: 500;
  font-size: 14px
`
//What happened here is that ParagraphCommon inherits the style of

//SubHeader, just like giving them the same styles. You can also 

//add specific styles within the quotes

const ParagraphCommon = styled(SubHeader)``

const SearchButton = styled.button`
height: 35px;
background-color: #192041;
flex: 0.2;
border: none;
color: #fff`

const ButtonGroup = styled.div`
width: 100%;
margin: 15px 0px;
display: flex;
align-items: center
`
const Button = styled.button`
  margin-right: 15px;
  width: 100px;
  padding: 7px;
  border: none;
  cursor: pointer;
  border-radius: 5px;
  color: ${props => props.textColor};
  background-color: ${props => props.bgColor}

//Here, styled-components receive props from the elements in the

//components, which are then accessed using this syntax, which 

//gives you the opportunity to do conditional styling.
`

//The React component
function App() {
  return (
    <Container>
        <Header>
          Free and Pro website templates for your business
        </Header>
        <SubHeader>
          Choose from over 300 fully responsive portfolio, blog and ecommerce templates
        </SubHeader>
        <Form>
          <InputContainer placeholder="Search all templates"/>
          <SearchButton>Search</SearchButton>
        </Form>

        <ParagraphCommon>
            Common searches
        </ParagraphCommon>

        <ButtonGroup>
            <Button bgColor="#f1c0de" textColor="#F037A5">Blog</Button>
            <Button bgColor="#e0c3fa" textColor="#8C5EB8">Business</Button>
            <Button bgColor="#d0fccd" textColor="#77D970">Portfolio</Button>
            <Button bgColor="#F9E4C8" textColor="#F78812">Ecommerce</Button>
        </ButtonGroup>
    </Container>
  );
}

export default App;

Enter fullscreen mode Exit fullscreen mode

More interesting view:

There are still a lot about styled-components, which you will love to check out. Click here for more

Feel free to follow and Connect with me on
πŸš€ Linkedin
πŸš€ Twitter

Thank you for reading!πŸŽ‰

styled-components tutorial completed/></p>

Top comments (37)

Collapse
 
joshkarges profile image
joshkarges

After using styled-components for a while, you'll be begging to use classNames again. Here's just a few limitations:

  1. styled class names are random stings that you have no control over, so looking at the DOM tree to debug something is a nightmare.
  2. Styled is really only good for styling a simple html tag. The moment you try to style any other component you'll realize things like the props to style are different from the props to render, and generic parameters don't transfer from a styled component. So say goodbye to ever using Typescript.
  3. The styled css props overwrite anything else giving through normal means like global css, or className, so your component becomes useless for sharing with others.

That's just a few. Sending in a simple string to the className is so much simpler and so much more powerful.

Collapse
 
arshadayvid profile image
David Asaolu

Thanks for sharing your thoughts Joshkarges

Collapse
 
damiisdandy profile image
damilola jerugba • Edited

I think you all should reduce the toxicity in this comment section, he is a fan of styled components and he prefers it to BEM, he made his suggestion not a statement, I personally out grew styled components but that doesn't mean someone shouldn't write about how they feel about it positively

Collapse
 
andresausecha profile image
Andres Ausecha Mosquera • Edited

Toxicity does not exist, we only give our opinions, the problem is to have the maturity to evaluate them and take a decision, if you do not have it I guess you career as developer won't be long

Collapse
 
ansile profile image
Ansile • Edited

I must say, styled components are kind of a newbie trap.

They sound cool, they look cool when you are writing your first code with them, so, you think, why not use them?

In these moments you don't think (unless you already have experience) about whether they are performant, easily maintainable or any of that other boring stuff.

And, by my experience, they aren't any of those:

  • they introduce an performance tax, and if your project ever grows to a point where performance starts to matter, there's not much to be done about it.
  • they are not compatible with Typescript, which is a huge deal breaker IMO
  • they are not lintable and not really checkable at compile-time at all. So support checking, autoprefixing and all other postcss features are automatically out of question

And frankly, the library (and the concept itself) are kinda old, so there were additions to css that do same kinds of things easier.

If you just need to represent component states - write a few classes. BEM or css-modules - frankly, does not really matter.
It's more clean - you separate different states into different classes, instead of opting for what is basically if expressions in one huge amorphous style.

If you really need to style something according to props, and there are more than, say, 3 states - use CSS-variables (if your supported browsers allow you to). It's simple, native and performant.

Collapse
 
frontendtony profile image
Anthony Oyathelemhi

I must say, styled components are kind of a newbie trap.

Very correct! Not long ago, I would install it when creating a new React project. Over time, I depended on it less and less, till the point where I no longer used it for anything. I think this coincided with when I started using Typescript/Tailwind

Collapse
 
arshadayvid profile image
David Asaolu

Thank you for the insights πŸ™Œ

Collapse
 
justynclark profile image
Justyn Clark

SC is old now people. It's just CSS-in-JS.
cssinjs.org

It's cool, I love it in some projects but can cause problems in others with homebrew static publishing solutions that give FOUC using it.

Also homeboy and others, please stop using "Stop using/doing" in these post titles. It's annoying!!!

Some would argue class names is back in a major way with Tailwind.

Collapse
 
arshadayvid profile image
David Asaolu

Alright noted. Thanks for sharing your thoughts on this.

Collapse
 
ctsstc profile image
Cody Swartz • Edited

If you're using something that supports CSS modules like Next JS I recommend trying out SCSS modules.

I am not exactly sure what you mean when you say you've been styling using classNames. Have you just been providing a raw object to classNames or have you tried CSS modules?

Collapse
 
michaelcurrin profile image
Michael Currin

I recommend adding syntax highlighting to your long code block.

Also I recommend being consistent with indenting the CSS styles and adding spaces at the start of your comments.

```jsx
// Header represents the h2 tag
const Header = styled.h2`
  color: #192041;
  font-weight: 700;
  margin-bottom: 15px;
  font-family: "Merriweather", serif;
`
```
Enter fullscreen mode Exit fullscreen mode
// Header represents the h2 tag
const Header = styled.h2`
  color: #192041;
  font-weight: 700;
  margin-bottom: 15px;
  font-family: "Merriweather", serif;
`
Enter fullscreen mode Exit fullscreen mode
Collapse
 
hsmr29 profile image
Hugo Martinez • Edited

SC is awesome to me... normally so that my component doesn't get mixed up with big SC code I just put the style components in a separate file and then import them, it really makes it easier for me to use SC than other ways of doing the same. And a plus is that there are several ways to have a good performance (without sacrificing much functionality) for more complex scenarios.

Of course, if you are only going to style a very small and static app, pure css I think is the best

Collapse
 
souzaluiz profile image
Luiz Henrique Souza

I think it's good to know the available styling options, I've used pure css, sass, styled-components and now I've decided to use css modules with sass and the classnames lib to facilitate conditional styles, and I'm really enjoying it, I believe there is no silver bullet, yes, there are tools that make the development much easier, finally, using one or the other depends a lot on the project and the dev's decision-making power.

Collapse
 
jurip89 profile image
jurip89

There's also:
Imprt {css} from 'styled-component'
Where you can assign to a variable a definite style.
If you style the same component in different ways you can do:
const example = styled(CustomButton)
background-color:blue;

Collapse
 
arshadayvid profile image
David Asaolu

Wow, thanks for sharing.
I will check that out also.

Collapse
 
grad profile image
Alex Grad

What about performance?

Collapse
 
arshadayvid profile image
David Asaolu

It's actually optimizes the loading of your webpages, by only loading the required css per page.

Collapse
 
grad profile image
Alex Grad

I didn't mean file sizes. I mean rendering time.

P.S. CSS modules also work with code splitting.

Collapse
 
andresausecha profile image
Andres Ausecha Mosquera • Edited

I do not suggest styled components at all. The syntax is more complex and hinder the reuse of code. Moreover you're using javascript to style your components instead of using pure css or SASS

Collapse
 
arshadayvid profile image
David Asaolu

It's actually pure CSS but just covered with JavaScript to reference the elements to be styled.
For the syntax, I actually find it very easy to install and use quickly.

Concerning the reuse of code, I don't really get that part, if you don't mind may be you can explain.
Cos, I think it's very reusable, with the passing of props into the styles, just like I did in the example above, thereby reducing the number of CSS styles you write.

Also, styled-components optimizes your webpages by loading only the required number of styles you need per component

Collapse
 
ivandack profile image
Ivan Dackiewicz

Hi David. I think AndrΓ©s means that with styled components you have all the styling code in the component, which is great to have that component as standalone, but means that you have to rewrite or copy the common styles that are more global or part of the theme when you are working on an app.

Also, the component file may end up being huge, with most of the content being style. Annoying to maintain.

Personally I'm trying a mix between Sass for common styles, and styled components for specific component styles. I won't recommend this yet because I'm still trying it out.

Thread Thread
 
arshadayvid profile image
David Asaolu

Oh! now I get it. I agree with you on this. Rewriting the styles can be timing consuming and huge componentsπŸ˜–

Nice, I actually use my index.css file for common styling or copy the styles sometimes.

Thread Thread
 
andresausecha profile image
Andres Ausecha Mosquera

Yeah, after 6 years as fullstack dev I found SASS the best tool for frontend styling, taking into consideration syntax, size, performance and maintainability. In any way, it's a matter of preference, if you like styled components and works for you then go ahead

Collapse
 
danielstrout profile image
DanielStrout

May either choose to do inline styling, import your CSS from an external style sheet, or even include it in your JavaScript file. SΓ©parer Un Couple Avec Une Photo

Collapse
 
damiisdandy profile image
damilola jerugba

Styled components really push the component driven ideology in react, ❀️ nice post

Collapse
 
arshadayvid profile image
David Asaolu

Thank you, glad you enjoyed it.

Collapse
 
xerohero profile image
Lorenzo Battilocchi

I use styled-components a lot in my dev projects. They are so handy for extending existing HTML tags 😊

Collapse
 
peter_brown_cc2f497ac1175 profile image
Peter Brown

How is this approach differ from just using Vue?

Some comments may only be visible to logged-in visitors. Sign in to view all comments.