Skip to content

Inherited prop className #4341

Closed
Closed
@mjurczyk

Description

@mjurczyk

Hey,

we have been recently using React (+Flux) in our project and we approached a quite intriguing problem. Following the WebComponents-like approach, we try to create a bunch of reusable components with similar behaviours. The problem arises when we want to put the same component, with the same 'logic', on a different view, with a different design (that be -> a different CSS class attached). We need to create the same component with different set of class' names (+usually a few default ones) and right now it seems to be only possible by passing props like classes or inheritedCls.

_tl;dr;_ It would be really cool if React passed the className from the component definition to it's actual DOM elements. That would save us creating and passing a classes props, ex.:

_Initialization in a parent component_:

class ParentComponentAlpha {
    render () {
      return (<MyComponent className={'contextual-styling-1'} />);
    }
};

class ParentComponentBeta {
    render () {
      return (<MyComponent className={'contextual-styling-2'} />);
    }
};

_Current way of appending 'inherited' classes_:

class MyComponent {
  propTypes: {
    classes: React.PropTypes.arrayOf(React.propTypes.string)
  },

  render () {
    var innerClasses = [
      'cmp--default',
      'cmp--mobile'
    ];  

    // Renders <div role="my-cmp" class="cmp--default cmp--mobile contextual-styling-."> ... </div>
    return (
      <div role={'my-cmp'} className={innerClasses.concat([...this.props.classes])}>
        Hello world
      </div>
    );
  }
};

_Nicer and simpler way:_

class MyComponent {
  render () {
    var innerClasses = [
      'cmp--default',
      'cmp--mobile'
    ];  

    // Still renders <div role="my-cmp" class="cmp--default cmp--mobile contextual-styling-."> ... </div>
    // Includes inner classes and implicitly adds the inherited class' names from ParentComponent
    return (
      <div role={'my-cmp'} className={innerClasses}>
        Hello world
      </div>
    );
  }
};

I would love to hear your opinions on that. We needed such functionality in the project and ended up passing the inherited class' names by props, which feels a little inelegant.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions