DEV Community

Karibash
Karibash

Posted on • Edited on • Originally published at karibash.Medium

Handle CSS units system in a type-safe way using TypeScript

I've created a library that can handle the CSS unit system in a type-safe way with TypeScript, and convert units from one to another.
If you find it useful, I'd appreciate it if you'd give it a star in the repository.

Install

npm install @karibash/pixel-units
Enter fullscreen mode Exit fullscreen mode

Usage

Handle the CSS unit system in a type-safe

import { Unit } from '@karibash/pixel-units';

const pixel: Unit<'px'> = '16px';
const rem: Unit<'rem'> = '1rem';
console.log({ pixel, rem });
// -> {pixel: "16px", rem: "1rem"}
Enter fullscreen mode Exit fullscreen mode

Convert CSS unit systems to each other

import { Unit, convertUnits } from '@karibash/pixel-units';

const pixel: Unit<'px'> = '32px';
const rem = convertUnits(pixel, 'rem');
console.log(rem);
// -> "2rem"
Enter fullscreen mode Exit fullscreen mode

Extract numeric values and units from the unit system

import { Unit, splitUnitValue } from '@karibash/pixel-units';

const pixel: Unit<'px'> = '32px';
const { value, unitSuffix } = splitUnitValue(pixel);
console.log({ value, unitSuffix });
// -> {value: 32, unitSuffix: "px"}
Enter fullscreen mode Exit fullscreen mode

Example of use in React

As an example, we will define a Wrapper component that can dynamically switch between the following paddings.

import React from 'react';
import { Unit } from '@karibash/pixel-units';

type Props = {
  padding: Unit<'rem'>
}
const Wrapper: React: FC<Props> = ({
  children,
  padding,
}) => {
  return (
    <div css={{ padding: `${padding}` }}>
      {children}
    </div>
  );
};

export default Wrapper;
Enter fullscreen mode Exit fullscreen mode

The padding property can be restricted so that it can only accept rem units.
If a value other than rem unit is specified, a compile error will occur.

import React from 'react';
import { Unit } from '@karibash/pixel-units';
import Wrapper from 'components/wrapper';

const Page: React:FC = () => {
  return (
    <>
      <Wrapper padding={'2rem'}>
        rem padding only
      </Wrapper>
      <Wrapper padding={'16px'}>
        compile error
      </Wrapper>
    </>
  );
};

export default Page;
Enter fullscreen mode Exit fullscreen mode

Top comments (0)