Giter Club home page Giter Club logo

react-bem-helper's Introduction

React BEM helper

npm version Build Status

A helper making it easier to name React.js components according to BEM conventions. It removes the repetition from writing the component name multiple times for elements and elements with modifier classes on them.

Why?

I found myself writing code like this a lot in my React components:

<div className="c-componentName">
  <div className="c-componentName__inner">
    Some test
    <button className="c-componentName__button c-componentName__button--left">Button</button>
    <button className="c-componentName__button c-componentName__button--right">Button</button>
  </div>
</div>

Compare that to SCSS, where you might write components something like this:

.c-componentName {
  background: red;

  &__button {
    text-transform: uppercase;

    &--left { float: left; }
    &--right { float: right; }
  }
}

react-bem-helper allows you to write in a similar-ish DRY fashion, taking away some of the repetition and hopefully making it easier to scan.

How does it work?

A new helper instance is created with a an options object or a string representing the name of the component (componentName) in this example. The instantiated helper receives up to three arguments (element, modifiers, extra classes). When called, it generates a simple object with props that should be applied to the React element: { classNames: 'componentName' }. You can use the spread operator ({...object}) to apply this object to the React element.

You can supply an options object to change helper's behaviour. For example, you can set the outputIsString option to true, and receive a plain string for the classname. A className prefix (like c-) option can be added as well.

Example

Here's how you would return the example HTML structure when using the helper.

var React     = require('react');
var BEMHelper = require('react-bem-helper');

var classes = new BEMHelper({
  name: 'componentName',
  prefix: 'c-'
});

module.exports = React.createClass({
  render: function() {

    return (
      <div {...classes()}>
        <div {...classes('inner')}>
          Some test
          <button {...classes('button', 'left')}>Button</button>
          <button {...classes('button', 'right')}>Button</button>
        </div>
      </div>
    );
  }
});

Usage

Installation

npm install react-bem-helper

Preparing the helper

Require the helper for your React component, and then instantiate a new instance of it, supplying an options object or a string representing the (block) name of the component.

var BEMhelper = require('react-bem-helper');

// Make 'componentName' the base name
var bemHelper = new BEMHelper('componentName')

// Or pass an options object with a prefix to be applied to all components and output set to return
// a string instead of an object
var bemHelper2 = new BEMHelper({
  name: 'componentName', // required
  prefix: 'mh-',
  modifierDelimiter: false,
  outputIsString: false
});

Options can be shared throughout a project by using withDefaults().

Constructor options

Name Type Default Description
name string Required The name of the BEM block.
prefix string '' A prefix for the block name.
modifierDelimiter string '--' The separator between element name and modifier name.
outputIsString boolean false Whether to return an object or a plain string from the helper.

Using the helper

When executed, the helper returns an object with a className property. When the helper is called without any arguments, its value will consist of the block name (prefixed if applicable)

var React     = require('react'),
    BEMHelper = require('react-bem-helper');

var classes = new BEMHelper('componentName');

module.exports = React.createClass({
  render: function() {
    return (
      <div {...classes('element', 'modifier', 'extra')} />
    );
    // Returns <div className='componentName__element componentName__element--modifier extra'/>
  }
});

Parameters

Name Type Default Description
element string '' The name of the BEM element.
modifiers string or string[] or object (*) '' A set of BEM modifiers.
extra string or string[] or object (*) '' A set of plain, non-BEM classes.

(*) These parameters can be either strings, array of strings, or an object whose keys will be applied if their values are evaluated as truthy (booleans or functions returning booleans). If any of the strings contain spaces, these will be split up.

Alternate Syntax

The bemHelper supports up to three arguments: element, modifiers, and extra classes, although an object containing any of these parameters is also supported:

function element() {
  var options = {
    element:   'element',
    modifiers: 'modifier',
    extra:     'extra'
  };

  return (
    <div {...classes(options)} />
  );
  // Returns <div className='componentName__element componentName__element--modifier extra'/>
};

Element

To generate a class like componentName__header, pass "header" as the first argument to the bemHelper.

var BEMHelper = require('react-bem-helper');
var bemHelper = new BEMHelper('componentName');

bemHelper('header'); // returns { className: 'componentName__header' }

You can also pass a configuration object instead of the first parameter:

bemHelper({ element: 'header' }); // returns { className: 'componentName__header' }

Modifiers

Modifiers can be added as a String, Array, or Object. For every modifier an additional class is generated, based upon either the block name or element name:

var BEMHelper = require('react-bem-helper');
var bemHelper = new BEMHelper('componentName');

bemHelper(null, 'active');
// or
bemHelper({ modifiers: 'active' });
// { className: 'componentName--active'}

bemHelper('lol', 'active funny');
// { className: 'componentName__lol componentName__lol--active componentName__lol--funny'}

bemHelper('lol', 'active');
// { className: 'componentName__lol componentName__lol--active'}

bemHelper('lol', ['active', 'funny']);
// { className: 'componentName__lol componentName__lol--active componentName__lol--funny'}

bemHelper('lol', {
  'active': true,
  'funny': false,
  'playing': function() { return false; }
  'stopped notfunny': function() { return true; }
});
// { className: 'componentName__lol componentName__lol--active componentName__lol--stopped componentName__lol--notfunny'}

If you pass an object as the modifiers argument, the helper will add the keys as classes for which their corresponding values are true. If a function is passed as a value, this function is executed.

Extra classes

This argument allows you to do add extra classes to the element. Like the modifiers, extra classes can be added as a String, Array, or Object. The behaviour is the same, except that the classes are added as passed, and no prefix or block name is added.

var BEMHelper = require('react-bem-helper');
var bemHelper = new BEMHelper('componentName');

bemHelper('', '', ['one', 'two']);
// or
bemHelper({ extra: ['one', 'two'] });
// { className: 'componentName one two'}

bemHelper('', '', {
  active: true,
  funny: false,
  playing: function() { return false;}
});
// { className: 'componentName active'}

As when using arguments, this syntax also supports arrays and objects as different ways of defining extra classes.

Output as string

By default, the helper outputs an object (e.g. { className: 'yourBlock' }). By supplying a constructor option or by setting custom defaults, you can have the helper return plain strings. It is a stylistic choice, but it can come in handy when you need to pass a class name in under a different property name, such as with react-router's Link component.

var React     = require('react'),
    Link      = require('react-router/lib/Link'),
    BEMHelper = require('react-bem-helper');

var classes = new BEMHelper({ name: 'componentName', outputIsString: true });

module.exports = React.createClass({
  render: function() {
    return (
      <Link className={classes('link')} activeClassName={classes('link', 'active')} />
    );
    // Returns <Link className='componentName__link' activeClassName='componentName__link componentName__link--active' />
  }
});

Modifier Delimiter / Default BEM naming scheme

For this project, I've chosen to use the .block__element--modifier naming scheme, because this seems to be the most common implementation. However, the official website on BEM considers this to be an alternative naming scheme.

If you like to use the official naming scheme, you can set the modifierDelimiter option to _ when creating the bemHelper, or set it as the default:

var classes = new BEMHelper({
  name: 'componentName',
  modifierDelimiter: '_'
});

// ...

module.exports = React.createClass({
  render: function() {
    return (
      <div {...classes('element', 'modifier')} />
    );
    // Returns <div className='componentName__element_modifier '/>
  }
});

withDefaults

Often, you will need to set defaults for your whole project, or maybe just one part of it. That's where BEMHelper.withDefaults() comes in. It creates a new constructor with one or more base defaults overridden. For example:

// custom-bem-helper.js

var withDefaults = require('react-bem-helper').withDefaults;

module.exports = withDefaults({
  // You don't need to override all defaults. If you want to (for example) keep the original '--'
  // modifier delimiter, just omit that field here.
  prefix: 'pfx-',
  modifierDelimiter: '_',
  outputIsString: true
});

Now, we just require our custom helper instead of 'react-bem-helper'.

// MyComponent.jsx
var React     = require('react'),
    BEMHelper = require('./custom-bem-helper');

var classes = new BEMHelper('MyComponent');

module.exports = React.createClass({
  render: function() {
    return (
      <div className={classes('element', 'modifier')} />
    );
    // Returns <div className='pfx-MyComponent__element pfx-MyComponent__element_modifier'/>
  }
});

Related projects

License

MIT License

react-bem-helper's People

Contributors

alexanderotavka avatar marcohamersma avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-bem-helper's Issues

Remove object-assign from dependencies

ES2015 was released two years ago. Let's remove it or use the rest operator with a pre-compilation tool!

90 lines vs

var _extends = Object.assign || function (target) { 
for (var i = 1; i < arguments.length; i++) { var source = arguments[i];
 for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { 
target[key] = source[key]; } } } return target; };

Version 1.4.0 breaks when extra contains is null or undefined

I'm using react-bem-helper passing down the className from props as an extra like this:

bem({
      modifiers: {...},
      extra: [
        status,
        className,
      ],
    })

Since version 1.4.0 it breaks when className is null/undefined with the following error message:

TypeError: Cannot read property 'split' of undefined
      at stringToArray (node_modules/react-bem-helper/index.js:21:16)
      at node_modules/react-bem-helper/index.js:48:27
      at Array.reduce (native)
      at listToArray (node_modules/react-bem-helper/index.js:47:17)
      at node_modules/react-bem-helper/index.js:102:29

Parameterized modifier

Hi, could you add a parameterized modifier?
In the original of BEM methodology modifier is _.

My proposal:

let classes = new BEMHelper({
    modifier: '_'
});

Discussion: Applying the helper + classnames

Currently, the classes are applied to elements by using the spread operator, like this:
<div {...bemHelper()}></div>

My rationale for using the spread operator over something like <div className={bemHelper()}></div> was very simple; for me it prevents the occasional case where I type “class” or “classNames” instead of “className”, and wanted to save myself those troubles. That said, I'm not convinced it's the best way of doing this.

I am thinking about what other/better ways to apply the classes to elements. If you have any feedback, it's very welcome.

Why the default prefix?

I was really happy to find this library and not having to write my own code since we use BEM quite a lot. One thing that bugs me is the default c- prefix.

I've never felt the need for prefixing. I'm aware that BEM used to differentiate between specific blocks b- and includes i- but I can't find any information about it in the current version. What is the rationale behind the default prefixing?

Personally, I wrap the helper class in a function which clears the prefix for me.

Make bem-helper as a main dependency

It would be nice to rename react-bem-helper with bem-helper or make another package as a main dependency. Really, the className property does not make any sense.
It's just an idea.

Provide an access to the name property

The problem:

let block = new ReactBlock({
	name: 'foo'
});

block.name // undefined

let { className, name } = block({ modifiers: ['bar'] });

name // undefined
className // .foo .foo--bar

Expected

let block = new ReactBlock({
	name: 'foo'
});

block.name // foo

let { name } = block({ modifiers: ['bar'] });

name // foo

Why I am interested in the problem:

Before

import * as ReactBlock from 'react-bem-helper';
import * as ReactCSSTransitionGroup from 'react-addons-css-transition-group';

class Preloader extends React.Component<void, void> {
	name = 'foo';

	block = new ReactBlock({ name: this.name })

	render (): JSX.Element {
		let block = this.block({ modifiers: ['bar'] });

		return <div { ...block } >
			<ReactCSSTransitionGroup transitionName={ this.name } >
				Loading...
			</ReactCSSTransitionGroup>
		</div>;
	}
}

After

import * as ReactBlock from 'react-bem-helper';
import * as ReactCSSTransitionGroup from 'react-addons-css-transition-group';

class Preloader extends React.Component<void, void> {
	block = new ReactBlock({ name: 'foo' })

	render (): JSX.Element {
		return <div { ...this.block({ modifiers: ['bar'] } } >
			<ReactCSSTransitionGroup transitionName={ this.block.name } >
				Loading...
			</ReactCSSTransitionGroup>
		</div>;
	}
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.