Skip to content

Selector class substitution. #102

Open

Description

@CubedEye

It would be great if there was a way to substitute class names from other files, possibly with a decorator such as :ref or :alias. This would allow parent elements to be able to provide a way to style children elements without having to either passing in extra classes or wrap it in extra element just to add extra classes to control it's styling.

Where is this useful?

Consider this trivial example when you have a component - for example some sort of <ButtonControlBar /> that takes a bunch of <MyAwesomeButton /> components.

<ButtonControlBar>
    <MyAwesomeButton />
    <MyAwesomeButton />
    <MyAwesomeButton />
</ButtonControlBar>

The ButtonControlBar component wants to add some margin between all of the children so that they are spaced nicely. We're going to want to add 5px of margin to the right of each button except the last. Using straight CSS we could do something like:

.button-control-bar > .my-awesome-button:not(:last-child) {
    margin-right: 5px;
}

With CSS Modules we could pass extra classes to each of the children, but in this case the MyAwesomeButton component hasn't been implemented with a way to do so (it's something 3rd-party that's also using CSS modules for example). Also we don't know the internal implementation of MyAwesomeButton so we can't assume it's just a <button> element.

We could instead wrap each of the children component in another element that you can add a class to allow use to control the style of the children, but this is just unnecessary wrapping to avoid what would be fairly straight forward with straight CSS .button-control-bar > .my-awesome-button.

Proposed Implementation

We could introduce a :ref pseudo-class that would allow us replace a selector value. I'm a fan of the pseudo-class as a declarative way to use the imports to replace classes. It's also less "magic" that just straight replacing the .childButton class where ever it appears.

// MyAwesomeButton.css-module
.my-awesome-button {
    background: red;
}

:export {
    myAwesomeButton: my-awesome-button
}

// ButtonControlBar.css-module
:import(MyAwesomeButton.css-module) {
    childButton: myAwesomeButton
}

.button-control-bar > :ref(.childButton):not(:last-child) {
    margin-right: 5px;
}

This provides a fairly fuss free way to achieve the above, with the added bonus that if we don't want to use MyAwesomeButton anymore, because <NextBigThingButton/> component is the more suited to the project we can just fix up the :import and the rest of the CSS doesn't need to be touched.

// NextBigThingButton.css-module
.next-big-thing-button {
    background: red;
}

:export {
    nextBigThingButton: next-big-thing-button
}

// ButtonControlBar.css-module
:import(NextBigThingButton.css-module) {
    childButton: nextBigThingButton
}

.button-control-bar > :ref(.childButton):not(:last-child) {
    margin-right: 5px;
}
...more rules that are using :ref(.childButton)

We built this behaviour into the webpack css-loader in this PR webpack/css-loader#212

Activity

  1. nkbt commented on Jan 6, 2016

    @nkbt

    Personally I would actually pass classes down or wrap them. Simple, no extra language necessary, no extra complications.

    <ButtonControlBar className={css.bar}>
        <MyAwesomeButton className={css.bt} />
        <MyAwesomeButton className={css.bt} />
        <MyAwesomeButton className={css.bt} />
    </ButtonControlBar>
    .bar {}
    .bt:not(:last-child) {
      margin-right: 5px
    }

    Can't figure out how it might be more difficult. Do I miss something?

  2. KJTsanaktsidis commented on Jan 6, 2016

    @KJTsanaktsidis

    I think in our case, the reason why we don't want to add classes to the children is because often the children are passed in. Consider something like the ButtonControlBar...

    // ButtonControlBar.js
    const css = require('buttonControlBar.css');
    const ButtonControlBar = React.createClass({
        render() {
            return (
                <div className={css.bar}>
                   {this.props.children}
                </div>
            );
        },
    });
    // SomeThingWithAButtonBar.js
    const Thing = React.createClass({
        render() {
            return (
                <ButtonControlBar>
                    <MyAwesomeButton text='foo' />
                    <MyAwesomeButton text='bar' />
                </ButtonControlBar>
            );
    });

    In the above example, the button control bar expects to be passed buttons as children. There are, as you point out, a few ways to skin this cat:

    • The consumer of the ButtonControlBar could put a class on the MyAwesomeButtons it creates. However, the fact that the button needs special styling inside the bar is really the bar's business, not the consumers, and it feels wrong to pollute the consumer with this responsibility
    • The ButtonControlBar could wrap each of its children in a div with a class. However, this introduces an extra level of DOM where it isn't strictly needed
    • The ButtonControlBar could clone each of its children and put a className on it. However, if the consumer also wanted to put a class on the button (because I want a purple button!) then the cloning process would have to take care to merge the className prop correctly (and this isn't automatic anymore with React.cloneElement the way it used to be with cloneWithProps). This seems like a good way to spend 10 minutes scratching your head wondering why your button is the wrong colour.

    I think the most elegant way to solve this problem is to just make use of the class that's already there! No extra DOM and no confusing prop merging.

  3. nkbt commented on Jan 6, 2016

    @nkbt
  4. KJTsanaktsidis commented on Feb 1, 2016

    @KJTsanaktsidis

    Hey, just wondering if anybody has any more input about this idea?

  5. renanvalentin commented on Feb 8, 2016

    @renanvalentin

    Hello guys, how did you ended up to solve this problem? I'm thinking in other workarounds but it seems too complicated, like having to pass props to child components.

  6. KJTsanaktsidis commented on Feb 8, 2016

    @KJTsanaktsidis

    @renanvalentin we're using our fork webpack/css-loader#212 in production :)

  7. renanvalentin commented on Feb 8, 2016

    @renanvalentin

    I've came up with a solution, it is more philosophical than technical:

    <ButtonControlBar>
        <MyAwesomeButton />
    </ButtonControlBar>
    
    .button-control-bar > .my-awesome-button {
       margin: 20px;
    }
    

    or

    .button-control-bar > button {
       margin: 20px;
    }
    

    Suppose I want to add an extra margin to my children buttons, that css selector should be fine, but thinking about components, thats an a bad idea, because:

    -> I need to know what class I'm using inside my component
    -> What if I change my HTML markup or changed the class name inside the component, this will result in breaking that css selector chaining;

    So I wrote this "Layout Component" responsible for extend my components:

    class Layout extends React.Component {
      componentDidMount() {
        let node = ReactDOM.findDOMNode(this);
        node.classList.add(this.props.className);
      }
    
      render() {
        return this.props.children;
      }
    }

    And I'm using it in this way:

    <ButtonControlBar>
         <Layout className={classes['pull-right']}>
             <MyAwesomeButton />
          </Layout>
    </ButtonControlBar>

    While I was writing this, I saw lots of problems on it, but that's ok hahahaha

  8. meta-meta commented on Mar 4, 2016

    @meta-meta

    Say I have the following React components:

    ModuleA renders

    <div styleName="moduleA">
        {props.children}
    </div>

    ModuleB renders

    <div styleName="moduleB"/>

    and some markup:

    <div>
        <ModuleA>
            <ModuleB/>
        </ModuleA>
        <ModuleA>
            <ModuleB/>
        </ModuleA>
        <ModuleA>
            <ModuleB/>
        </ModuleA>
        [...]
    </div>
    .moduleB { 
    
    }
    
    .moduleA {
      &:nth-child(even) {
        .moduleB { /* doesn't work because the real classname of ModuleB is not known in ModuleA*/
          background-color: #000;
        }
      }
    
      &:nth-child(odd) {
        .moduleB  {
          background-color: #fff;
        }
      }
    }

    What's the idiomatic css-modules approach to this? Pass odd/even classnames into ModuleB props?

  9. LeZuse commented on Aug 8, 2016

    @LeZuse

    Also running into this concern a lot. A typical usecase is a parent component's hover state changing it's children styles somewhere deeper in the component tree.

    The point is that by introducing the hover style you are effectively coupling those components together.

    I haven't found a better solution than creating a "shared stylesheet" that expresses this connection between those components in question and then importing this stylesheet in both components, effectively adding them a new class name.

    Pseudocode below:

    ComponentA

    import ComponentAStyle
    import hoverStyles
    
    <div className="ComponentBStyle.myWhateverStyle hoverStyles.hoverParentStyle">
      <div>
        // ComponentB does not need to be rendered directly here
        // There might be even more components in between
        <ComponentB />
      </div>
    </div>
    

    ComponentB

    import ComponentBStyle
    import hoverStyles
    
    <div className="ComponentBStyle.myWhateverStyle hoverStyles.hoverChildStyle"></div>
    

    hoverStyles

    .hoverParentStyle:hover .hoverChildStyle {
      /* hover styles */
    }

    You can even put the hoverStyles directly in either ComponentAStyle or ComponentBStyle if you are more or less sure about the implications.
    We use https://github.com/JedWatson/classnames for easier className manipulation.

    In more simple scenarios I totally agree with @nkbt's #102 (comment) approach.

  10. geelen commented on Aug 9, 2016

    @geelen
    Member

    Yeah I'm starting to weaken on this. I reckon we should just add it as an escape-hatch, since while I don't think you need to use these "contextual styles" as often as you might think (prop-passing is still the "CSS Modules" way), I'm no longer convinced it should be a hard rule.

    The hover state is a good example, there are hit-testing reasons why you might need to attach :hover to a particular element in the DOM, but change the style of a descendant element.

  11. CubedEye commented on Aug 9, 2016

    @CubedEye
    Author

    @geelen @KJTsanaktsidis

    We've been using our fork of the css-loader from here webpack/css-loader#212 for the last 6 months and it seems to be working well. Ideally we're trying to use CSS-modules as intended, but when you want to build some sort of UIKit that has a bunch of pieces that interact with each other without giving the developer an entry point for poking additional classes on to the elements (as you would enable with a props based solution) then having a way to substitute classes is super useful.

    I know that in an ideal world having encapsulation is a great thing. But in the example of a UIKit above, you've already commited to all the pieces being coupled together so the CSS is likely going to be coupled anyway.

    The proposal of a :ref() decorator works really well because the CSS won't compile if a referenced class goes missing, which is really what you want if you're going to do something like this.

  12. geelen commented on Aug 9, 2016

    @geelen
    Member

    Cool, well this would probably need to be made into a change in https://github.com/css-modules/postcss-modules-extract-imports but given how often this gets asked for, and how in... 12 months we've not come up with a better way, unless @sokra has a really strong objection I reckon we should just go ahead with it.

    Glad your fork has been working out for you while I've been a bit absent. If you feel like doing up a new PR to postcss-modules-extract-imports that would be great, otherwise I'll get a chance to look at it next week some time.

  13. lijunle commented on Feb 16, 2017

    @lijunle

    This is awesome dicusssion. I suppose this is defined as :import pseudo-selector in ICSS spec:

    The places within the CSS file that are checked for localAlias are:

    • In any declaration value: e.g. border: 1px solid localAlias;
    • In any selector: e.g. .localAlias .MyComponent {}
    • In a media query argument: e.g. @media screen and localAlias

    I tried to leverage :import in CSS-Loader but the second bullet is not supported. It could be great if CSS Module Spec could support it.

  14. pferreir commented on Apr 9, 2018

    @pferreir

    Just ran into this problem. Any news on this?

  15. buschtoens commented on Jul 12, 2018

    @buschtoens

    Relates to #147.

  16. added a commit that references this issue on May 7, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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