mapPropsToClasses

Maps a component's props to class names.

Features

  • Supports boolean and string props
  • Appends className prop to allow extending class names
  • Optional root class applied before other classes

Import the function from @minddrop/utils.

import { mapPropsToClasses } from '@minddrop/utils';
export interface ButtonProps {
size?: 'small' | 'medium' | 'large';
color?: 'primary' | 'danger';
disabled?: boolean;
}
export const Button: React.FC<ButtonProps> = ({
children,
className,
color,
disabled,
size = 'medium',
}) => (
<button className={mapPropsToClasses( { className, size, color, disabled }, 'button', )} >
{children}
</button>
);

A Button component with default props would render as:

<button class="button size-medium" />

A Button component with the following props:

<Button disabled size="small" color="primary" className="custom-button" />

Would render as:

<button class="button size-small color-primary disabled custom-button" />

Boolean props are mapped simply as the prop name, with camelCase names converted to kebab-case. For example, a fullWidth prop would add a full-width.

String props are mapped as [name]-[value]. For example, a size="small" prop would add a class of size-small.

The className prop is appended to the generated class names.

Falsy props do not generate any classes.

The rootClass value is prepended to the generated class names.

class="rootClass [prop classes] className"

mapPropsToClasses(
props: Record<string, string | boolean>,
rootClass?: string,
);
PropTypeDefault
props*objectNo default value
rootClassstrinNo default value