DEV Community

NDREAN
NDREAN

Posted on • Updated on

A new CSS-in-JS package for SolidJS

It can be advantageous to write some components with some local CSS rules. This package leverages the native CSS nesting and produces a fast CSS-in-JS/Component solution: there is no parsing, just directly adding a style element to the <head> tag of the DOM.

We have produced a less than 700B package to write CSS-in-JS for SolidJS: https://github.com/ndrean/solid-css/.

This package uses document so is not suited for SSR.

It exports the function css, styled, createGlobalStyles and keyframes.

You write a template CSS string and pass it to the css function to produce a class:

const bluediv = css`
  background-color: bisque;
  color: midnightblue;
`;
Enter fullscreen mode Exit fullscreen mode

and use it:

<div class={bluediv}>I am blue</div>;
Enter fullscreen mode Exit fullscreen mode

You can design animated components. An example with a styled component:

const rescale = keyframes`
  0% {transform: scale(0.5)}
  100% {transform: scale(1)}
`;

const AnimSurf = (props) => styled("span", props)`
  font-size: ${props.size}em;
  animation: ${rescale} 2s ease infinite;
`;
Enter fullscreen mode Exit fullscreen mode

and use it:

<AnimSurf size={3}>πŸ„</AnimSurf>;
Enter fullscreen mode Exit fullscreen mode

Conditional classes

You have two ways to use it. Define a function or object that returns CSS strings:

const styles = (props) => {
  base: `
    cursor: pointer;
    font-size: ${props.size ?? 1}em;
    border-radius: 0.3em;
    padding: 0.3em;
  `,
  danger: `
    color: red;
    animation: ${rescale} 1s ease infinite;
  `,
  disabled: `
    pointer-events: none;
    opacity: ${props.opacity};
  `;
}
Enter fullscreen mode Exit fullscreen mode

You can write:

const Btn = (props)=> styled('button', props)`
  ${styles(props).base +
  props.danger ? styles(props).danger : ""}
`

<Btn>Base button</Btn>
<Btn danger={true} onClick={()=> alert('danger')}>Danger button</Btn>
Enter fullscreen mode Exit fullscreen mode

To make life easier, the primitive styled can read the props and sets the class when the styles are defined as above:

const Button = (props) => styled("button", props)`
  ${styles(props).base}
  ${styles(props)}
`;
Enter fullscreen mode Exit fullscreen mode

We can use it:

<Button size={3}>Base button</Button>

<Button
  disabled
  className={css`
    box-shadow: 6px -6px teal;
  `}
  >
  Disabled with shadow
</Button>
Enter fullscreen mode Exit fullscreen mode

You can use reactive styles with the style prop, overwrite classes for styled components, create conditional CSS depending on the props, and define global styles. Check the Readme and the example.

Top comments (0)