Styletron: React Component Styles on Steroids

K - Apr 2 '17 - - Dev Community

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.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player