I decided to bring the articles from my blog here to dev.to and following the order, the first article I wrote was about styled-components, so here we go..
While the front end development is experiencing the modular advantages of components, there are several ways to styling them, as CSS, SASS, CSS Modules, etc.
I would like to introduce you to my new favorite one: styled-components, which nowadays is increasingly popular on the frontend.
Created by Max Stoiber, styled-components is a library that allows you to write CSS code inside Javascript, which means you won't need to import .css file into your page anymore. In addiction to organize your code better, you also have the possibility to reuse the created components in the same project just calling them or in another project just copying the .js file into it.
I had my first experience with styled-components on a ReactJS project I started developing last year. I was presented to this fantastic library through a learning live on twitch.tv and once I used it I've never wanted to return to the old ways of styling. You will see why!
Installation
To set up styled-components, run the following command (if you use npm) in your project directory:
npm install --save styled-components
Voilà!
The following example creates a simple button component, already styled:
import styled from "styled-components";
const Button = styled.button`
background-color: #3a4042;
color: #f5f5f5;
border: 1px solid #f5f5f5;
border-radius: 4px;
padding: 0.25em 1em;
margin: 1em;
font-size: 20px;
cursor: pointer;
`;
render(
<Button>
Send
</Button>
);
The result:
Now you saw how easy is to styling your component, you must know that you can style any component!
The following example is a modificated one from styled-component website:
const h2 = ({ className, children }) => (
<a className={className}>
{children}
</a>
)
const StyledH2 = styled(h2)`
color: #db7093;
font-weight: bold;
`;
render(
<>
<h2>Unstyled, boring Title</h2>
<StyledH2>Styled, exciting Title</StyledH2>
</>
);
The result:
You can also pass tag names into the styled() factory call, as "div", "section", not only components.
Changing based on props
You can also change a component state based on a prop you set and adapt this component to have another style or behavior.
This example shows how to change the size of the component Tag
by setting its prop small
to true.
const Tag = styled.h2`
font-size: 40px;
letter-spacing: 2px;
background-color: #db7093;
color: #f5f5f5;
padding: 20px 18px;
${({ small }) =>
small &&
css`
font-size: 25px;
padding: 8px 8px;
`};
`;
render(
<div>
<Tag>Normal Tag</Tag>
<Tag small>Small tag</Tag>
</div>
);
Check the result below:
One of my favorites things in styled-components is how you can pass props of a component to the DOM node that is mounted.
This examples shows how to styled-components passes the prop categoryColor
with the border color to the Button
component, if no value is sent by the prop then the default color #ffba05
is used.
const Button = styled.button`
color: #000000;
width: 100px;
margin-right: 5px;
border-radius: 4px;
border: 4px solid
${({ categoryColor }) => categoryColor || "#ffba05"};
`;
render(
<div>
<Button>yes</Button>
<Button categoryColor={"#db7093"}>no</Button>
</div>
);
Check the result below:
Apart from the improved experience for developers, styled-components provides:
- Automatic critical CSS: styled-components keeps track of which components are rendered on a page and injects their styles and nothing else, fully automatically. Combined with code splitting, this means your users load the least amount of code necessary.
- No class name bugs: styled-components generates unique class names for your styles. You never have to worry about duplication, overlap or misspellings.
- Easier deletion of CSS: it can be hard to know whether a class name is used somewhere in your codebase. styled-components makes it obvious, as every bit of styling is tied to a specific component. If the component is unused (which tooling can detect) and gets deleted, all its styles get deleted with it.
- Simple dynamic styling: adapting the styling of a component based on its props or a global theme is simple and intuitive without having to manually manage dozens of classes.
- Painless maintenance: you never have to hunt across different files to find the styling affecting your component, so maintenance is a piece of cake no matter how big your codebase is.
- Automatic vendor prefixing: write your CSS to the current standard and let styled-components handle the rest.
Hope you enjoy styled-components as much as I did. :)
Top comments (31)
I don't see why people like Styled Components that much. For me the syntax is confusing, it feels repetitive to write CSS when I'm defining the component and I honestly see no advantage over using Tailwind, for example.
This might be due to my background on JS/frontend development being quite small compared to my PHP/backend development experience, but so far, I rather stick with Tailwind, feels more natural to me.
What I find most confusing is the whole backtick thingy to write CSS. How can this weird syntax be clearer than using class names? Doesn't it lead to repeated CSS definitions being spread over components?
Styled-components was built with javascript in mind by using the ES6 feature template literals (the backtick thingy) which is becoming more commonly used among front-end devs. I personally enjoy styled-components because template literals allow more dynamic usecases based on props but the biggest benefit for me is readability and organization. My gripe with tail-wind is that a bunch of classNames quickly makes a component harder to read whereas styled-components doesn't and allows you re-name simple html elements like '
' to '' so a component actually becomes more readable. Co-locating styled components with the React component makes it easier to locate styles too.
and yes, there can be instances of repeated CSS definitions but that's mostly dependent on how you architect your styled-components as they are both composable and extensible.
I really agree with your reply! In the beginning I also committed a lot of repetitions with styled-components, but over time I organized better and reduced it.
Thank you for the words!
Can't believe I'm just now seeing this! I would love to know how your organization has changed. Everyone's approach is so interesting.
I use tailwind along with styled components or emotion by using twin.macro package and with that I can write tailwind classes in the backticks
Hey Praveen that's super intersting but I'm weary of potential performance cost. Have you found this to be the case? If not what are some other potential downsides?
Exactly my opinion as well. Instead of writing
display: flex
in every styled component, why not write the Tailwind classflex
and use plain css classes?! Utility css classes are amazing.Tailwind is just styled components implemented with CSS classes instead of JS.
Back in the day we didn't have Tailwind and emulated that behavior with JS, now I'd say this workaround isn't needed anymore.
I'm not sure I understand. I wanted to point out the power of CSS classes that do one thing and only one thing. For instance, the
text-center
class that aligns your text to the center.It's so powerful because you don't need anything else, no JS, no styled components, just boring CSS. Bonus: almost anyone that reads that class will assume that it just aligns the text to the center.
You cans till use classes when using styled components.
You can create more layers of abstraction. For example create a FlexBox styled component which is a div that comes built in with flex. It can also receive props that will tell it how to align and justify (for example).
Then, when creating a new div you can actually create it from styled(FlexBox)
Tailwind and styled component have the same issues, as any other solution. With Tailwind the same developer that repeat
display:flex
everywhere will repeat theflex
class everywhere.Also, creating consistence design you can have a Text component that receives a boolean prop named "center".
So if you see you know it is aligned to the center.
My biggest gripe with these components is:
you lose intelesense, linting, autocomplete, colour preview, drop-shadow UIs.
All colour segregation which improves readability (css key value parts, layered values).
Hmm strange, I don't lose any of those except for linting (which imo seems somewhat negligible with component driven development where all styles are localized to individual components and a well structured/maintained theme). The only time I lose the other features is when I'm missing backticks or semi-colons.
image on the left is what i see usually when someone mentions styled components, wall of one colored text. On the right is what i'm used and expect when working with styles, auto-complete, syntax error highlights, etc.
edit: image upload failed, fallback image example of what i mean imgur.com/a/skNhRw0
Ah I see now. Thanks for sharing...I'm not sure what editor you use but VS code does have an extension that addresses this. I can understand how the lack of these features makes SC less desirable.
Also I'm glad you brought up linting because I looked at the docs again and you can add a stylelint
Thanks, good to know that there are extensions that fix all my gripes. I've not tried styled components so I've only seen them in posts like these which show them as a block of yellow text. Not sure why most introductory posts showcase them like that.
Typically the kind of answer you hear from backend devs (no offense, really, just exposing a difference of mindset).
Of course you can do a lot with Tailwind. But you still stay inside the limits of a framework. I've heard designers saying things like "I want to do that, but it'll be tricky to do with Tailwind, so I won't". And that's sad. You can tweak Tailwind. But if you have to do dozens of tweaks and fight with the classes, in the end, just write CSS, it'll be faster and you HTML will be way cleaner.
After comparing a lot of different styling libraries I ended up choosing styled-components for my website too, for the same reasons that you mention in your post.
Ironically, the one issue I had with it was it would sometimes mess up the generated class names in the production build. 🙃
Wow! I never went through this! Did you only use styled-components or something else along with?
No other styling libraries, but I did use it with some other tools that might also do some weird stuff for production builds.
It’s been several months since I ran into the issue, so I assume they’ve fixed it by now. 😄
This is very likely! :P
Especially with typescript you can create fast, reliable applications. But I think Sass and other approaches still have a place in web development.
But I would definitely use styled-components if I want to do it fast and easy.
Thanks for the article
That's it! there is room for all, but if you wanna go fast and easy.. \o
You are welcome! :)
In my opinion this whole css/sass/bem/modules/styled-components discussion is a matter of preference and requirements.
Depending on the project and developer in charge the necessity of using one approach over another may differ.
It is better to separate css into a file instead of mixing with JSX.
This is great! I'm more convinced now to learn Styled Components.
That is nice! I'm sure you won't regret it!
Agree with all you mention, this is best approach to style. The very thought of someone still using something else terrifies me.
but aren't styled components are like running autoprefixer and postcss in browser
For me i prefer to use CSS modules over styled component it put me in the groove of writing CSS the old way