DEV Community

NDREAN
NDREAN

Posted on • Updated on

New CSS-in-JS lightweight packages for React and Preact

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/Component for:

These packages uses document so is not suited for SSR.

It exports the primitives: css, styled, createGlobalStyles and keyframes.

The api is very close to standard libraries.

Class

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

You can use it:

<p className={bluediv}>A nice paragraph</p>
Enter fullscreen mode Exit fullscreen mode

Styled component

You can use styled components in the form below. An example with an animation via keyframes:

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

You can 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.

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, extend classes for styled components, define global styles. Check the Readme and the example.

Top comments (0)