I tried to understand the argument made for styled components vs. ‘traditional’ CSS. But when reviewing these arguments I found out that they typically use bad code as proof for their point.
See e.g. the following SCSS code:
$blue = #5DBCD2;
@mixin button-styles($bg-color, $color) {
background: $bg-color;
color: $color;
border: none;
border-radius: 0.20em;
&:hover{
background: darken($bg-color, 6%);
cursor: pointer;
}
}
.button {
@include button-styles(#ddd, black)
}
.button--primary {
@include button-styles($blue, white)
}
To pair with a simple component along the lines of:
const Buttons = props => (
<>
<button className="button">Default</button>
<button className="button--primary">Primary</button>
</>
)
export default Buttons
The suggested alternative is:
import themeVars from "myTheme"
import styled from "styled-components"
import { darken } from "polished"
const Button = styled.button`
background: ${({ background }) => background || "#ddd"};
color: ${({ color }) => color || "black"};
border: none;
border-radius: 0.25em;
:hover {
background: ${({ background }) => darken(0.05, background || "#ddd")};
}
`
const Buttons = props => {
const { blue } = props.theme.colors;
return (
<>
<Button>Default</Button>
<Button background={blue} color={"white"}>Primary</Button>
</>
)
}
export default withTheme(Buttons)
You might think this is better when you’re used to writing the earlier mentioned SCSS/SASS.
Learn CSS again.
With good ol’ CSS you’d write:
.button {
background: #ddd;
color: #000;
border: none;
border-radius: 0.25em;
&:hover{
background: #ccc; /*estimation*/
/* cursor: pointer; <- also don't: another discussion */
}
}
.button--primary {
background: #5DBCD2;
color: #fff;
&:hover{
background: #4DACC2; /*estimation*/
}
}
The HTML would be:
<button class="button"></button>
<button class="button button--primary”></button>
In BEM, what the original example seemed to be using, modifiers modify, they are not the style itself as well. Please, front-end devs: Let’s not (programatically) over duplicate & complicate things.
Note, in contrast to some of the pure CSS folks, I’m not anti-SCSS. I actually do use SCSS; to store the typical theme variables for margins, colours etc. I even use an occasional function to darken something or calculate some ratio’s (typically at settings level). Even an occasional include to replicate an almost similar border style for totally unrelated objects. But never to overcomplicate things.
Enjoyed this? Follow me on Mastodon or add the RSS, euh ATOM feed to your feed reader.
Dit artikel van murblog van Maarten Brouwers (murb) is in licentie gegeven volgens een Creative Commons Naamsvermelding 3.0 Nederland licentie .