An open API service indexing awesome lists of open source software.

https://github.com/wavevision/class-name

🖍 Create and format BEM class names for React components
https://github.com/wavevision/class-name

bem classname classnames css format-bem react react-components typescript utility

Last synced: over 1 year ago
JSON representation

🖍 Create and format BEM class names for React components

Awesome Lists containing this project

README

          

Wavevision s.r.o.


Class Name

[![CI](https://github.com/wavevision/class-name/workflows/CI/badge.svg)](https://github.com/wavevision/class-name/actions/workflows/ci.yml)
[![Coverage Status](https://coveralls.io/repos/github/wavevision/class-name/badge.svg?branch=master)](https://coveralls.io/github/wavevision/class-name?branch=master)
[![npm](https://img.shields.io/npm/v/@wavevision/class-name)](https://www.npmjs.com/package/@wavevision/class-name)

Create and format BEM class names for React components. The formatter uses [simplified](https://github.com/inuitcss) BEM syntax.

## Installation

Via [Yarn](https://yarnpkg.com)

```bash
yarn add @wavevision/class-name
```

or [npm](https://npmjs.com)

```bash
npm install --save @wavevision/class-name
```

## Usage

Simple React component

```typescript jsx
import React, { useState, FunctionComponent } from 'react';
import className, { USE_VALUE } from '@wavevision/class-name';

interface ComponentProps {
align: string;
booleanProp: boolean;
nullableProp: string | null;
stringProp: string;
}

interface ComponentState {
visible: boolean;
}

// Define base class name with props and state behaving as modifiers
const componentClassName = className(
'component-class',
() => ({
// if booleanProp value is truthy, 'booleanProp' will be used as modifier
booleanProp: true,
// if stringProp value is truthy then the value will be used
stringProp: USE_VALUE,
// use callback for custom modifiers, string returned will be used
customModifier: ({ props }) => (props.nullableProp ? 'custom' : null),
// if a non-string truthy value is returned, key will be used
anotherModifier: ({ state }) => state.visible,
}),
);

// We can also have modifiers defined only if some condition is met
const anotherClassName = className(
'another-class',
({ props, state }) => {
if (props.nullableProp !== null) {
// the whole set of modifiers will be created only if nullableProp is not null
return { stringProps: USE_VALUE, customModifier: () => true };
}
if (state.visible) {
// this set will be created only if state.visible is true
return { customModifier: () => true };
}
},
);

const Component: FunctionComponent = props => {
const [visible] = useState(false);
const className = componentClassName({ props, state: { visible } });
const nextClassName = anotherClassName({ props, state: { visible } });
return (




// modifiers can be nullable and will be used only if not null



);
};
```

will output following when rendered

```typescript jsx

```

```html







```