Skip to content

A React higher-order component (HOC) that maps alternative boolean props to a single prop.

License

Notifications You must be signed in to change notification settings

BradEstey/boolean-variants

Repository files navigation

boolean-variants

A React Higher-Order Component (HOC) that maps alternative boolean props to a component while maintaining the original component props.

// Before 🥱
<Button variant="primary" size="lg">
// After ✨
<Button primary lg>

Installation

npm install boolean-variants

Usage

Assume you have BaseButton component that has a variant prop and a size prop. Used like:

<BaseButton variant="primary" size="lg">

Use withBooleanVariants to pass an object of arrays of possible values and their corresponding prop keys.

import { withBooleanVariants } from 'boolean-variants'

const Button = withBooleanVariants(BaseButton, {
  variant: ['primary', 'secondary', 'outline', 'destructive'],
  size: ['xs', 'sm', 'lg', 'xl'],
} as const) // <--- `as const` is required in TypeScript!

Now you can use boolean props to set the same prop values.

<Button primary lg>

You can even combine them.

<Button variant="primary" lg>

Attempting to use an explicit prop with a boolean prop variant or two boolean prop variants of the same group will throw a runtime error.

<Button variant="primary" secondary>
// ❌ Throws a prop conflict error.
<Button primary secondary>
// ❌ Throws a variant collision error.

About

A React higher-order component (HOC) that maps alternative boolean props to a single prop.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published