{"id":19487994,"url":"https://github.com/entomb/react-class-composer","last_synced_at":"2025-04-25T18:32:36.467Z","repository":{"id":62239884,"uuid":"557905186","full_name":"entomb/react-class-composer","owner":"entomb","description":"Simple tool to compose css classnames based on component props","archived":false,"fork":false,"pushed_at":"2023-01-17T01:27:55.000Z","size":144,"stargazers_count":5,"open_issues_count":5,"forks_count":0,"subscribers_count":2,"default_branch":"main","last_synced_at":"2025-04-14T04:55:22.131Z","etag":null,"topics":["classnames","css","react","tailwindcss"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/entomb.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2022-10-26T14:22:25.000Z","updated_at":"2024-05-22T19:28:55.000Z","dependencies_parsed_at":"2023-02-10T07:15:58.049Z","dependency_job_id":null,"html_url":"https://github.com/entomb/react-class-composer","commit_stats":null,"previous_names":[],"tags_count":3,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/entomb%2Freact-class-composer","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/entomb%2Freact-class-composer/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/entomb%2Freact-class-composer/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/entomb%2Freact-class-composer/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/entomb","download_url":"https://codeload.github.com/entomb/react-class-composer/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":250872359,"owners_count":21500805,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["classnames","css","react","tailwindcss"],"created_at":"2024-11-10T20:48:13.913Z","updated_at":"2025-04-25T18:32:36.177Z","avatar_url":"https://github.com/entomb.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# ![React Class Composer](https://user-images.githubusercontent.com/57768/198602737-edb226d8-e482-48a1-b7e6-d1b61821108f.png)\n\nSimple tool to compose css classnames based on component props\n\n## Install\n\n```bash\n  $ npm install react-class-composer\n  $ yarn add react-class-composer\n```\n\n## Motivation\n\n**react-class-composer** was built as a tool for creating low level basic building block components for new design systems or UI libraries that use utility-css frameworks to style components (like tailwind).\n\nthere are definitely other libraries that achieve this, and if you are looking to solve that problem and **react-class-composer** does not fit your needs, I encourage you to check them out: [useFancy](https://www.npmjs.com/package/use-fancy), [use-utility-classes](https://www.npmjs.com/package/use-utility-classes), [React With Class](https://www.npmjs.com/package/react-with-class)\n\n---\n\n## How does it work?\n\nuse `createComponent()` we can create and forward a native HTML component:\n\n```ts\nimport { createComponent } from \"react-class-composer\";\n\ntype BoxProps = {\n  display?: \"flex\" | \"block\" | \"inline\";\n};\n\nexport const Box = createComponent\u003cBoxProps\u003e(\"div\", {\n  base: \"box-base\",\n  options: {\n    display: {\n      flex: \"display-flex\",\n      block: \"display-block\",\n      inline: \"display-inline\",\n    },\n  },\n});\n```\n\n### Using the component:\n\n```jsx\n  \u003cBox display='flex'\u003e\u003cBox\u003e\n  \u003cBox display='inline'\u003e\u003cBox\u003e\n  \u003cBox display='block'\u003e\u003cBox\u003e\n```\n\n### HTML Output:\n\n```html\n\u003cdiv className=\"box-base display-flex\"\u003e\u003c/div\u003e\n\u003cdiv className=\"box-base display-inline\"\u003e\u003c/div\u003e\n\u003cdiv className=\"box-base display-block\"\u003e\u003c/div\u003e\n```\n\n# Hooks\n\n## `useClassComposer()` Hook\n\nthis hook acts like the `createComponent` function, but lets you deal with all the component outer shell.\nit returns a classname based on a config file, and requires a `config` and `props` object.\n\n```tsx\nimport React from \"react\";\nimport { useClassComposer } from \"react-class-composer\";\n\ninterface Props {\n  size: \"small\" | \"medium\" | \"large\";\n  something: React.ReactNode;\n}\n\nexport const YourComponent: React.FC\u003cProps\u003e = (props) =\u003e {\n  const { className } = useClassComposer\u003cProps\u003e(\n    {\n      base: \"base-class\",\n      options: {\n        size: {\n          small: \"small-class\",\n          medium: \"medium-class\",\n          large: \"large-class\",\n        },\n      },\n    },\n    props\n  );\n\n  return (\n    \u003cdiv className={className}\u003e\n      your component\n      {props.something}\n    \u003c/div\u003e\n  );\n};\n```\n\n## `useClassname()` Hook\n\nthis hooks just compiles the `@ClassDefinition` object into memoized string of classnames. its kind of like [`clsx()`](https://www.npmjs.com/package/clsx). it takes a `config` object and optionally a `React.DependencyList` array.\n\n```tsx\nimport React from \"react\";\nimport { useClassname } from \"react-class-composer\";\n\nconst ComponentWithClass: React.FC = ({ props }) =\u003e {\n  const className = useClassname(\n    [\n      \"btn\",\n      \"btn-something\",\n      { hover: \"btn-hover\" },\n      () =\u003e (props.something ? \"btn-something\" : \"btn-not\"),\n    ],\n    props\n  );\n\n  return \u003cbutton className={className}\u003eclick me!\u003c/button\u003e;\n};\n```\n\n# the `@ClassDefinition` type\n\n```ts\nexport type ClassDefinition = string\n| ClassDefinition[];\n| ((value) =\u003e ClassDefinition)\n| { [key: string]: ClassDefinition }\n```\n\nanytime you can define a class, you can use any combination of the following values:\n\n## `String`\n\n```js\n  options: {\n      prop: {\n        a: \"simple\",\n        b: \"multiple classes in the same string\" // will be .split(\" \") before parsing\n      }\n  }\n```\n\n## `Array`\n\nany array of `@ClassDefinition` values will be flattened and parsed.\n\n```js\n  options: {\n      prop: {\n        a: [\"simple\", \"array\"],\n        b: [\"multi\", [\"level\", \"array\"]],\n        c: [() =\u003e \"string\", {obj: \"string\"}]\n      }\n  }\n```\n\n## `Functions`\n\nyou can use functions to generate dynamic classnames. functions can return any valid `@ClassDefinition` excluding function\n\n```js\n  options: {\n      prop: {\n        a: () =\u003e \"some-class-name\"\n      },\n      anotherProp: (value) =\u003e `prop${value}`\n  }\n```\n\n## `Objects`\n\nany object beyond the first level (used to parse prop values) will be exploded into prefixed classes like `key:value`. all keys need to be string, but the value can be any `@ClassDefinition`\n\n```js\n  options: {\n      prop: {\n        a: \"a-value\", // will apply `a-value` if \u003c... prop=\"a\" /\u003e\n        b: \"b-value\" // will apply `b-value` if \u003c... prop=\"b\" /\u003e\n        c: {hover: 'color-red'}// will apply `hover:color-red` if \u003c... prop=\"c\" /\u003e\n      },\n\n  }\n```\n\n# Mixers\n\n[TODO]\n\n# `$` and `$$` Prefixes\n\n[TODO]\n\n---\n\n# Full Example\n\n([view Button.tsx](test/Example/Button.tsx)) ([view Tests](test/createComponent.test.tsx))\n\n```tsx\nimport {\n  createComponent,\n  mixAddClass,\n  mixFunction,\n  mixRemoveClass,\n} from \"react-class-composer\";\n\ntype ButtonProps = {\n  size: \"tiny\" | \"small\" | \"medium\" | \"large\";\n  variant?: \"none\" | \"outline\" | \"filled\";\n  rounded?: boolean;\n  anotherOption?: \"on\" | \"off\";\n  dynamicOptions?: number;\n} \u0026 Partial\u003c{\n  // alias:\n  round: ButtonProps[\"rounded\"];\n  v: ButtonProps[\"variant\"];\n}\u003e;\n\nexport const Button = createComponent\u003cButtonProps, \"button\"\u003e(\"button\", {\n  \"button\",\n  {\n    /**\n     * Base: base classes, will always be applied\n     */\n    base: [\n      \"btn\",\n      { hover: [\"btn-hover\", \"text-bold\"] }, // {key: 'value'} pairs will be exploded into prefixed classes like `key:value`\n      () =\u003e \"btn-base\", // you can use functions to return a string or @ClassDefinition object\n    ],\n\n    /**\n     * Mix: mix functions allow for conditional class toggling based on the multiple props.\n     */\n    mix: [\n      // mixAddClass will add classes if all the conditions are true\n      mixAddClass([\"size.tiny\", \"variant.outline\"], \"size-tiny-outline-mix\"),\n\n      // mixRemoveClass will remove a class if all the conditions are true\n      mixRemoveClass(\n        [\"size.tiny\", \"variant.filled\"],\n        [\"btn-base\", { hover: \"btn-hover\" }, \"hover:text-bold\"]\n      ),\n\n      // mix functions support wild card checks:\n      mixRemoveClass([\"data-something.a\"], [\"btn-base\"]),\n\n      // you can run your own mix functions\n      mixFunction([\"anotherOption.*\", \"disabled.true\"], (css) =\u003e\n        css.add(\"any-anotherOptions-disabled-true\")\n      ),\n\n      // or simply just pass in a mix object.\n      { when: [\"type.reset\"], run: (css) =\u003e css.add(\"btn-reset\") },\n      // you can match any prop, even if its a native HTML element one\n      {\n        when: [\"formNoValidate.true\"],\n        run: (css) =\u003e css.add(\"form-no-validate\"),\n      },\n    ],\n\n    /**\n     * Alias: prop shortcuts for other options\n     */\n    alias: {\n      // v=\"outline\" is interpreted as variant=\"outline\"\n      v: \"variant\",\n      round: \"rounded\",\n    },\n\n    /**\n     * Options: options are [key,value] pairs, where the key is the prop name\n     */\n    options: {\n      size: {\n        // you can use string\n        tiny: \"padding-tiny margin-tiny\",\n\n        // or any combination of string[]\n        small: [\n          \"padding-medium\",\n          \"margin-medium\",\n          [\"text-medium\", \"font-something\"],\n        ],\n\n        // also supports () =\u003e string\n        medium: () =\u003e `medium-stuff class-returned-by-function`,\n\n        // any object key will be parsed as \"prefixed\" class name\n        large: {\n          large: [\"text\", \"font\", \"padding\"],\n          key: { abc: [\"a\", \"b\", \"c\"], num: [\"n1\", \"n2\", \"n3\"] },\n        },\n      },\n\n      // use $ as a prefix to mark a prop as \"native\" (comes from the native HTML element we are extending)\n      $type: {\n        submit: \"btn-submit\",\n      },\n\n      variant: {\n        none: \"\",\n        outline: \"bg-white-500 text-black border border-gray-400\",\n        filled: \"bg-teal-200 text-white\",\n      },\n      rounded: \"rounded-2xl\",\n      anotherOption: {\n        on: \"option-on\",\n        off: \"options-off\",\n      },\n\n      // dynamic options via function\n      dynamicOptions: (value) =\u003e {\n        if (value \u003c 50) return \"less-than-50\";\n        if (value \u003e 50) return \"more-than-50\";\n        return [\"value-is-50\", \"dynamic-options-50\"];\n      },\n\n      // use $ as a prefix to mark a prop as \"native\" (comes from the native HTML element we are extending)\n      $disabled: \"btn-disabled\",\n\n      // use $$ as a prefix to apply classes if a prop is present, ignoring what value it has\n      $$title: \"btn-has-title\",\n\n      // we can also target data-attributes:\n      \"data-something\": {\n        a: \"something-a\",\n        b: \"something-b\",\n      },\n    },\n  },\n  {\n    // defaults, will apply classes as if \u003c... variant=\"none\"\u003e\n    variant: \"none\",\n  }\n);\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fentomb%2Freact-class-composer","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fentomb%2Freact-class-composer","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fentomb%2Freact-class-composer/lists"}