Styletron is an universal toolkit for component-oriented styling. It falls into the CSS in JS category. Styletron works great with React but can be used with other frameworks or plain JS as well.
Looking for v3 docs or v3 to v4 migration guide?
import { styled } from "styletron-react"; export default () => { // Create a styled component by passing // an element name and a style object const Anchor = styled("a", { fontSize: "20px", color: "red", }); return <Anchor href="/getting-started">Start!</Anchor>; };
Styletron provides styletron-react with some handy React utilities. In the example above, we use the styled
function to create a styled React component.
What is happening behind the scene?
<html>
<head>
<style>
.foo {
font-size: 20px;
}
.bar {
color: red;
}
</style>
</head>
<body>
<a href="/getting-started" class="foo bar">Start!</a>
</body>
</html>
Styletron processes the style object and creates two atomic classes. The class names are auto-generated. So you don't have to worry about naming methodologies! That's great! What's less great? The generated names are not stable and will change all the time so you should never target them. If you need a stable selector for something as e2e tests, you should add data-test-id
attribute.
Since Styletron uses the <style />
tag, you can use media queries and other selectors as well. You could not do that with inline styles! Check Concepts for more information about how classic CSS translates into CSS in JS.
Finally, the Anchor
component is created and its className
prop is set to ".foo .bar"
.
Styletron generates styles only when absolutely needed. This concept is also known as critical rendering path. This means that your browser never needs to process CSS rules that are not being used. Styletron does declaration-level de-duplication known as Atomic CSS. It dramatically reduces the redundancy of CSS rules. Also, Styletron is pretty compact and will add less than 8kB (gzip) to your bundle.
If you want to make sure that your CSS scales well with the size of application, you might need to reach for some additional tooling. For example, a comparable approach called CSS Modules requires you to use Webpack and its css-loader. To improve the developer experience even further, many projects also rely on post/pre-processing with PostCSS or SASS.
On the other hand, using Styletron means adding just an additional npm module into your project. It doesn't require a specific compiler or bundler setup.
Your styles are written in JavaScript and co-located with your components. It is the same developer experience as using inline styles but without any drawbacks. You can use standard modularization and code-splitting techniques. As long as your application has Styletron installed, everything works!
There are many other benefits that CSS in JS brings. For more context, you can check the React: CSS in JS presentation.
For more technical details, you can also read the Virtual CSS with Styletron article.