Import Attribute Selectors from CSS Module

910 Views Asked by At

I am working on a react hook that will load styles from an (s)css module based on the props passed to a component. It looks something like this:

import { useState, useEffect } from 'react';

export type SCSSModule = Record<string, string>;
export type Styles = Record<string, any>;

export default function useStyles(scssModule: SCSSModule, styles: Styles): string {
  const [className, setClassName] = useState<string>('');

  useEffect(() => {
    const classNames: string[] = [];

    for (const k in styles) {
      const attrSelector = `[${k}='${styles[k]}']`;

      if (k in scssModule) {
        classNames.push(scssModule[k]);
      } else if (attrSelector in scssModule) {
        classNames.push(scssModule[attrSelector]);
      } else {
        throw new Error(`Missing style for ${k}=${styles[k]}`);
      }

      setClassName(classNames.join(' '));
    }
  }, [styles]);

  return className;
}

In theory, I want us to be able to write an (S)CSS module like this:

.grid {
  display: grid;
}

[gutter='small'] {
  grid-gap: 8px;
}

[gutter='medium'] {
  grid-gap: 16px;
}

[gutter='large'] {
  grid-gap: 24px;
}

[columns='1'] {
  grid-template-columns: repeat(1, 1fr);
}

[columns='2'] {
  grid-template-columns: repeat(2, 1fr);
}

[columns='3'] {
  grid-template-columns: repeat(3, 1fr);
}

and be able to use the hook like this:

import styles from "./Grid.module.scss"
import useStyles from "../hooks/useStyles"
import type { FC } from "react";

const { grid } = styles;

interface GridProps {
  gutter?: "small" | "medium" | "large";
  columns?: number;
}

const Grid: FC<GridProps> = ({ gutter, columns, children }) => {
  const className = useStyles(styles, { grid, gutter, columns });
  return <div className={className}>{ children }</div>
}

and what this should do is load the styles from the css module based on a pattern:

  • for every key passed, see if there is an exact match for the key, then load its style, so you can load styles directly
  • for every key/value (prop) passed to the hook, load the styles for [propName='propValue']

It seems though, I cannot load definitions like [columns='1'] {} from a CSS module.

I know, I could change the pattern so that instead of defining the styles for the props as [propName='propValue'] {} I could define them as .propName-propValue {} or something, but I want to see if it is in any way possible to use the [propName='propValue'] {} syntax.

Do you see a way to do this?

0

There are 0 best solutions below