DEV Community

shadowtime2000
shadowtime2000

Posted on • Originally published at h.shadowtime2000.com on

What is CSS-in-JS?

What is CSS-in-JS?

So you have all probably heard of CSS-in-JS frameworks and libraries such as emotion, styled-components, and goober.

What is CSS-in-JS

CSS-in-JS libraries follow many different patterns. But usually, they end up allowing you to do one thing:

  1. Allow you to create unique CSS classes from JavaScript

Basically, you would typically use it like this:

const myButtonsClassName = cssInJsLibraryFunctionHere({
    color: "red",
    "text-align": "center"
});

// Or with tagged template literals

const myButtonsClassName = css`
    color: red;
    text-align: center;
`
Enter fullscreen mode Exit fullscreen mode

Some libraries (like styled-components) let you create React components from those styles, and allow you to create dynamic values for styling.

const Button = styled.button`
    color: ${({ dark }) => dark ? "dark" : "white"}
`;

<Button />
<Button dark />
Enter fullscreen mode Exit fullscreen mode

Conclusion

CSS-in-JS is a pattern that allows you to write CSS styles inside your JavaScript.

Top comments (0)