/compound-builder

Easy-to-use compound builder

Primary LanguageTypeScriptMIT LicenseMIT

compound-builder

NPM version NPM downloads Size

It's small but powerful. You can build compound components with declarative code.

Also, it supports type safety as shown in the picture below.

compound-builder is typesafe


🕹 Demo Repository 🕹
Sample Counter

Basic example

import { compoundBuilder } from "compound-builder";
import constate from "constate";

import useSampleLayout from "./index.hook";
import { SampleBody, SampleFooter, SampleHeader } from "./index.style";

export const [SampleProvider, useCount, useCountIncrement, useCountDecrement] =
  constate(
    useSampleLayout,
    (value) => value.count,
    (value) => value.increment,
    (value) => value.decrement
  );

const SampleLayout = compoundBuilder(SampleProvider, {
  // You can specify any key you want. (e.g. chicken, pizza)
  Header: SampleHeader,
  Body: SampleBody,
  Footer: SampleFooter,
});

export default SampleLayout;

When used as shown above, the developed compound component will be affected by the Sample Provider context. This means that you can access the context through hooks like useCount.

If you develop compound components through a builder, you can use them as follows:

import SampleLayout from "@/components/Organisms/layouts/sample";
import CounterSection from "@/components/Organisms/sections/sample/CounterSection";

const SamplePage = () => {
  return (
    <SampleLayout>
      <SampleLayout.Header>
        <SampleHeaderSection />
      </SampleLayout.Header>

      <SampleLayout.Body>
        <CounterSection />
      </SampleLayout.Body>

      <SampleLayout.Footer>
        <SampleFooterSection />
      </SampleLayout.Footer>
    </SampleLayout>
  );
};

export default SamplePage;

Installation

npm:

npm i compound-builder

Yarn:

yarn add compound-builder

API

compoundBuilder<T>(wrapperComponent, Record<string, React.component<T>)

If you add sub-components to the compound component to be specified, you can handle the types as they are when using them.

Contributing

If you find a bug, please create an issue providing instructions to reproduce it. It's always very appreciable if you find the time to fix it. In this case, please submit a PR.

If you're a beginner, it'll be a pleasure to help you contribute. You can start by reading the beginner's guide to contributing to a GitHub project.

When working on this codebase, please use yarn. Run yarn examples to run examples.

License

MIT © KZ-Lucas