DEV Community

K
K

Posted on

Styletron: React Component Styles on Steroids

TL;DR Here is a repository with a working example. :)

If you are up to date with the newest React trends, then you probably heard about styled-components. It's a library that helps greatly with the creation of, as the name implies, styled components.

Styletron now tries to get this approach to the next level. It's basically React for CSSOM instead of DOM. It tries to create the minimal amount of CSS to get the work done, offering performance benefits over other approaches that simply create a class for every style.

How

First you need a StyletronProvider at the root of your application, that will handle your styled components. It takes a Styletron object as prop. This object can use a style element as its render target, like React uses a DOM element to render its components.

const styleSheet = document.createElement("style");
document.head.appendChild(styleSheet);
const styletron = new Styletron([styleSheet]);

const vdom = (
  <StyletronProvider styletron={styletron}>
    <Application />
  </StyletronProvider>
);

...

ReactDom.render(vdom, renderTarget);
Enter fullscreen mode Exit fullscreen mode

Later you can use the styled() function to create a styled version of a element or component of your choice. The idea is that your component works as before.

Here a div:

const Square = styled("div", {
  background: "grey",
  width: "100px",
  height: "100px"
});
Enter fullscreen mode Exit fullscreen mode

But it could also use a reference to a component class:

const BigIcon = styled(Icon, {
  color: "red",
  font: "3em"
});
Enter fullscreen mode Exit fullscreen mode

It is also possible to pass a function that will get the props as an argument. This allows to return style objects based on the props content.

const Indicator = styled("h1", props => ({
  background: props.active ? "green" : "grey",
  color: props.active ? "white" : "black",
  textAlign: "center"
}));
Enter fullscreen mode Exit fullscreen mode

Styletron will take care of the heavy lifting in the background, calculating minimal amount of classes needed to create this styling and your components work as before.

Top comments (3)

Collapse
 
hadfieldn profile image
Nathan Hadfield

Have you considered making a tag template function that would support the same syntax as styled-components? One of the things I really like about styled-components is that I can use my IDE's support for CSS autocompletion. Also this would make it easy to transition from styled-components to Styletron.

Collapse
 
kayis profile image
K

This isn't my library, I just wrote about it, because I thought it deserves some promotion :D

As far as I can tell (and I may be wrong) the idea of the Object literals is to allow typing via TypeScript or something.

Collapse
 
hadfieldn profile image
Nathan Hadfield

I see. Thanks for a helpful article!