0.3.0 • Published 3 months ago

react-classy-component v0.3.0

Weekly downloads
-
License
MIT
Repository
-
Last release
3 months ago

react-classy-component

A library to make it more convenient to create properly typed React components using Tailwind CSS.

Install

yarn

yarn add react-classy-component

npm

npm install react-classy-component

Usage

Simple example

// Button.tsx
import { rcc } from "react-classy-component";

export const Button = rcc.button`bg-blue-500 text-white p-2 rounded`;

This will generate a React.ButtonHTMLAttributes<HTMLButtonElement> component, giving you all the prop validation and intellisense you are used to.

If you are using the className prop, anything passed in will be merged with the classes you specified in your component. Any other props will be passed on to the underlying component.

// Somewhere else in your app
import { Button } from "./Button";

const Component = () => (
  <Button className="m-5" type="button">Click me!</Button
)

Will render 👇

<button class="bg-blue-500 text-white p-2 rounded m-5" type="button">
  Click me!
</button>

Preview

Conditional rendering

You can specify custom props to render variants of your component.

export const Button = rcc.button<{
  primary?: boolean;
  danger?: boolean;
}>`
text-white p-2 rounded
${{
  primary: "bg-blue-500",
  danger: "bg-red-500",
}}
`;
<Button primary>Click me!</Button>
<Button danger>I am dangerous!</Button>

Now bg-blue-500 will only be rendered if the primary prop is truthy. And, you guessed it, bg-red-500 will only be rendered if danger is truthy.

<button class="text-white p-2 rounded bg-blue-500">Click me!</button>
<button class="text-white p-2 rounded bg-red-500">I am dangerous!</button>

Advanced conditions

If you need more advanced conditions, instead of using a simple object, you can pass in a function that returns the classes you want to apply. The function will be called with the props passed in to your component.

interface Props {
  variant?: "primary" | "secondary";
}

export const Button = rcc.button<Props>`
text-white p-2 rounded
${(props: Props): string => {
  if (props.variant === "primary") return "bg-blue-500";
  if (props.variant === "secondary") return "bg-yellow-500";

  return "bg-gray-500";
}}
`;

And to use it as a secondary button 👇

<Button variant="secondary">A secondary button</Button>
0.3.0

3 months ago

0.2.1

3 months ago

0.2.0

3 years ago

0.1.0

3 years ago