Skip to content

Proposal: CSS Class Composition #291

Closed

Description

@ticky

Here at Buildkite, we’ve got a slightly odd situation with our styles. We’ve traditionally used Basscss in an attempt to make sure we’re DRY and things are conceptually simple, and partly in an effort to keep engineers and CSS usually-far-apart.
We’ve now hit the point where we want some bespoke stuff, and I think Styled Components best fills the gap we have - we want simplicity on one end and explicity and specificity on the other. Basscss fills the former, Styled Components the latter.

I’ve found, with this, that I want some sort of composition functionality. Given that the current approach would seem to be, implement your styles in one place, and set the classes you expect to compose elsewhere, it feels like it’s a bit less than ideal!

After a bit of fiddling I’ve settled for now on the workaround of setting defaultProps.className on the styled component;

const Title = styled.h1`
  font-size: 1.5em;
  text-align: center;
  color: palevioletred;
`;

Title.defaultProps = {
  className: 'meow nya'
};

// => <h1 className="meow nya kZQsGZ" …

That way, the composition is in the same “place” as the Styled Component definition – but I wonder if the Styled Components API itself should explicitly support this!

Having thought about the API surface area, it feels like a JS approach isn’t perhaps the best, as I feel while it would probably be the simplest solution to engineer, it would probably produce a rather more confusing and ugly API;

const Title = styled.h1.withClass("meow nya")`
  font-size: 1.5em;
  text-align: center;
  color: palevioletred;
`; // => <h1 className="meow nya kZQsGZ" …

// ostensibly the same as
styled('h1').withClass("meow nya")//…

Instead, I’d propose an approach making use of the ability to extend syntax with PostCSS, like this;

const Title = styled.h1`
  @compose 'meow nya';
  @compose 'purr';

  font-size: 1.5em;
  text-align: center;
  color: palevioletred;
`; // => <h1 className="meow nya purr kZQsGZ" …

A few more things which would require consideration;

  • Class names are computed based on a hash of the style before PostCSS has any insight into it. Is it okay for otherwise identical class definitions with different composition at-rules to generate identical CSS?
  • For the most part, Styled Components is pretty hands-off about your CSS - there aren’t any special rules and other than auto prefixing, it doesn’t let you plug in PostCSS plugins of your own - is this sort of extra manipulation in the spirit of Styled Components?

Partly adapted from a brief, hit-and-run discussion in the Styled Components gitter 😜

Activity

  1. ticky commented on Dec 5, 2016

    @ticky
    Author

    Bonus round: CSS technology soup;

    import { meow, nya } from 'some-css-module.css';
    
    const Title = styled.h1`
      @compose ${meow};
      @compose ${nya};
    
      font-size: 1.5em;
      text-align: center;
      color: palevioletred;
    `; // => <h1 className="c_windows_system32_contrived-examples_some-css-module__meow c_windows_system32_contrived-examples_some-css-module__nya kZQsGZ" …
  2. geelen commented on Dec 6, 2016

    @geelen
    Member

    Ok so I do think this is worth supporting, as using immutable, atomic classnames for the backbone of your styling then using SC to write per-component deviations is kinda neat, and a nice way for people to ease in to more JS-based abstractions.

    But @composes is tricky. We support nesting in SC but @composes can't work within nested components, so we'll have the same logical inconsistency that CSS Modules suffers, where composes: works mostly like @extend in Sass but not quite. So I'm very hesitant to add some CSS extension that only works at the root level. I'm actually hesitant to add anything custom in the CSS blocks tbh, since one of the points of this project is to move more things into JS but keep the same fluidity of writing CSS.

    That said, there are two options that I can see fitting with our existing API. These are:

    const Title = styled.h1`
      ${ compose(' meow nya') }
      ${ compose('purr') }
    
      font-size: 1.5em;
      text-align: center;
      color: palevioletred;
    `

    Then we need compose() to return some special object that we detect during the interpolation and apply to the parent component instead of the CSS snippet we're building. That's... possible but a bit unexpected, and suffers from the same problem that it doesn't work with nesting.

    My other idea is this, a throwback to the good old days of HAML :)

    const Title = styled('h1.meow.nya.purr')`
      font-size: 1.5em;
      text-align: center;
      color: palevioletred;
    `

    Semantically, that makes more sense to me, because styled(x) means you're styling an x. And it's kinda ok that that x has classes already attached. But it's a bit of a weird mashup of syntaxes.

    What do you think?

  3. ticky commented on Dec 6, 2016

    @ticky
    Author

    I’m with you on not trying to extend your syntax! Totally makes sense and the other option would kind of be a pandora’s box 📦

    Interpolation of a compose object seems, frankly, even messier?

    Perhaps you’re onto the right thing with that latter option. I’d be a little wary to mix concerns in the initial argument like that - the fewer things we’re “parsing” the better, I think 😉

    How about something like this?

    const Title = styled('h1', 'meow nya purr')`
      font-size: 1.5em;
      text-align: center;
      color: palevioletred;
    `

    Leveraging the second argument means you could, ostensibly, keep your shortcut functions very simple - you’d probably be able to just use bind to make this simple, in fact…

    // src/constructors/styled.js
      const styled = (tag: Target, composeClass: string) =>
        (strings: Array<string>, ...interpolations: Array<Interpolation>) =>
          styledComponent(tag, css(strings, ...interpolations), composeClass)
    
      /* Shorthands for all valid HTML Elements */
    // Thanks to ReactDOMFactories for this handy list!
      //...
      styled.h1 = styled.bind(null, 'h1')
    const Title = styled.h1('meow nya purr')`
      font-size: 1.5em;
      text-align: center;
      color: palevioletred;
    `
  4. geelen commented on Dec 6, 2016

    @geelen
    Member

    Hmm, the second argument thing I'm not so keen on. But this kinda would work:

    const Title = styled.h1.classes('meow nya purr')`
      font-size: 1.5em;
      text-align: center;
      color: palevioletred;
    `

    The implementation of that would be much nicer, too. Only once the template function is actually evaluated does the component get created, so chaining a method like classes just creates a new template function with a closure over the classnames. This is all relevant to #227's changes that I'm working on at the moment, the difference being that this would be a user-facing API so it needs to be... nice for humans :)

  5. smeijer commented on Dec 6, 2016

    @smeijer

    I would suggest naming the method className instead of classes, to be more in line with react.

    const Title = styled.h1.className('meow nya purr')`
      font-size: 1.5em;
      text-align: center;
      color: palevioletred;
    `;

    But if you're going with this, I would also suggest a style or css method, just for synthetic suger:

    const Title = styled.h1
      .className('meow nya purr')
      .style`
        font-size: 1.5em;
        text-align: center;
        color: palevioletred;
    `;
  6. geelen commented on Dec 6, 2016

    @geelen
    Member

    Whoa, very interesting! I only picked classes because I had thought about applying a complex object ala the classnames library, but given these are defined at the top level (not inside a render method with access to props) that probably doesn't make sense. However, the className prop would still be used to pass extra classes in so I probably don't want to collide the name.

    I kinda don't mind this syntax as a kind of 'expanded' mode btw:

    const Title = styled.h1
      .displayName('Title')
      .identifier('Title-a1b2c3d4')
      .classes('meow nya purr')
      .css`
        font-size: 1.5em;
        text-align: center;
        color: palevioletred;
      `
    
    <Title className='extra'>
    // => <h1 class="Title-a1b2c3d4 e9f8a7b6 meow nya purr extra">...

    This sits kinda well with me as a flexible way to attach extra configuration to a component as it's created. The displayName and identifier stuff is gonna be injected by the babel transform, btw, so don't worry about that, so only classes|classNames and css|styles (still open on the naming here) would be added to the public API.

    I'm gonna give this a crack and see how it feels.

  7. ticky commented on Dec 6, 2016

    @ticky
    Author

    This sounds like a pretty promising compromise! Would this make calling .css mandatory or would it be skippable at the top (styled.h1 or styled('h1')) level?

    In the mean time I’ve actually realised I could actually totally just make a simple wrapper component which lets you do this;

    const Title = styled(classed('h1', 'meow nya purr'))`
      font-size: 1.5em;
      text-align: center;
      color: palevioletred;
    `

    I guess thinking about it this way I’d actually still be open to this concept being rejected as “not accepted to be styled-components’ responsibility” 😜

  8. geelen commented on Dec 7, 2016

    @geelen
    Member

    The .css would be optional yeah. And yeah your idea would work but then you've got an extra layer of components. I'd like to avoid that if possible. I've finished my proof-of-concept, I think it looks kinda good.

  9. codepunkt commented on Dec 9, 2016

    @codepunkt
    Member

    To be honest, i don't see the benefit here. Imho, styled-components main goal should be to enable simple, feature-rich styling of components. I would not mix that with other style systems such as resets, grids or whatever which can very well be added using attributes of the styled components:

    const Title = styled.h1`
      font-size: 1.5em;
      text-align: center;
      color: palevioletred;
    `;
    
    // in a render method
    <Title className="meow nya" />
    
    // => <h1 className="meow nya kZQsGZ" …

    Isn't this already possible and fine as is?

  10. ticky commented on Dec 9, 2016

    @ticky
    Author

    @code-punkt: the thing we have here though is a mix of approaches, like it or not we have a mature app which is already using Basscss. We're not mixing with a reset or a grid, but the proposed approach allows us to better encapsulate the way our existing classes interact with the specific enhancements we plan to use styled-components for.

    Yes, that syntax is possible, but tha syntax requires us to physically separate our use-specific styles (which we are authoring with styled-components) and the class-per-thing approach of Basscss, when ultimately in each component we make in this way, the former relies on the latter.

  11. codepunkt commented on Dec 10, 2016

    @codepunkt
    Member

    @ticky So that syntax is possible - glad to hear. What i don't get is the "physical separation" argument. Why is my proposed syntax not a good idea?

  12. ticky commented on Dec 12, 2016

    @ticky
    Author

    Like I said, it has an advantage in encapsulation.

    Your styled component definition will very likely exist outside your react component class definition. There could be dozens or hundreds of lines between the definition of the styled component and the actual use of it.

    Thus, the classes it may in fact rely on can be logically, conceptually and physically separated (by many lines of code) from the definition of the styled component CSS, which would actually seem to be counter to the encapsulation goals of styled components.

    And yes, the use of third-party styles could be argued to be counter to those same goals, however, functionality already exists within styled components to apply additional class names, so I contend that styled components does not in fact intend to obviate their use in your code entirely.
    This functionality, therefore, merely ensures that they are applied more consistently where needed.

  13. geelen commented on Dec 13, 2016

    @geelen
    Member

    Yeah I'm with @ticky on this one too. The whole point of styled components' API versus, say, Glamor, is this deliberate encapsulation. Let me see if I can demonstrate:

    /* glamor-ish-style */
    <div {...css({
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center'
        })}>
      <h1 {...css({
            color: 'palevioletred',
            background: 'papayawhip'
          })>
        Hello World
      </h1>
    </div>
    /* styled components style */
    const Outer = styled.div`
      display: flex;
      align-items: center;
      justify-content: center;
    `
    
    const Title = styled.h1`
      color: palevioletred;
      background: papayawhip;
    `
    
    <Outer>
      <Title>Hello World</Title>
    </Outer>

    Now, of course in Glamor you'd extract out the styling blocks to variables but you don't have to. In Styled Components you're (mostly) forced to name everything. By naming something you give it a real layer to attach meaning to, and something that can travel between files. Styled Components is basically driven off the assertion that that separation is really good — that all your styling is contained in a logical unit.

    In that vein, this doesn't pass the test:

    const Outer = styled.div`
      justify-content: center;
    `
    
    const Title = styled.h1`
      color: palevioletred;
      background: papayawhip;
    `
    
    <Outer className="flex flex-center">
      <Title>Hello World</Title>
    </Outer>

    But a proper classes method (or some custom interpolation) does. So... I think we should add it. It also has implications for #227 (which currently implements classes but @mxstbr doesn't like the syntax yet 🙃)

    Any other API options I'm missing?

  14. k15a commented on Dec 13, 2016

    @k15a
    Member

    Another API would probably:

    const Title = styled.h1`
      color: palevioletred;
      background: papayawhip;
    `
    
    Title.classes  = "flex flex-center"

    IMO this doesn't look as clean as your approach but is a more React style (propTypes, defaultProps)

  15. 30 remaining items

  16. xcoderzach commented on Jan 14, 2017

    @xcoderzach
    Contributor

    it should be straight forward to implement, here's an example of how you might do it.

    class StyledComponent {
    
      constructor() {
        // React would never pass a string as props when
        // initializing a component
        if(typeof arguments[0] === 'string')
          return styled(StyledComponent).apply(null, arguments)
        }
        // Otherwise do your usual constructor stuff.
      }
    
    }
  17. jason-henriksen commented on Jan 14, 2017

    @jason-henriksen

    I'm actually working on implementing this with a slightly different api. But I'm new to javascript and npm exports so I'm learning as I go. I'll post a pull request when I getting running, hopefully next week.

  18. vdanchenkov commented on Jan 14, 2017

    @vdanchenkov
    Member
    const MyDisabledButton = MyButton`
      color: grey;
    `

    Looks interesting, but I want to mention that it will be harder to detect that MyDisableButton is a styled-component in a plugin. If MyButton is imported from another file the only way to detect is to analyze contents of template literal and I would not rely on it.

  19. xcoderzach commented on Jan 14, 2017

    @xcoderzach
    Contributor

    @vdanchenkov Is that necessarily a bad thing? That just means you can extend component styles without the styled-components dependency.

    EDIT:

    It could actually be a benefit if you can extend a library's styled-components without the dependency.

  20. geelen commented on Jan 14, 2017

    @geelen
    Member

    I don't like this api at all, sorry. Apart from being incredibly surprising (wait it's a React component and a template literal function?) I think the implementation is... deeply unsettling (constructors not returning instances of their class):

    const MyDisabledButton = MyButton`
      color: grey;
    `

    This api is totally fine though:

    const MyDisabledButton = MyButton.extend`
      color: grey;
    `

    So much cleaner!

  21. ticky commented on Jan 15, 2017

    @ticky
    Author

    Doesn’t the existing infrastructure pretty handily support style composition anyway?

    const MyButton = styled.button`
      color: blue;
    `
    
    const MyDisabledButton = styled(MyButton)`
      color: grey;
    `
  22. geelen commented on Jan 15, 2017

    @geelen
    Member

    Yeah we're ditching that for consistency. If you call styled(X) you should always get a component that wraps X and passes className to it

  23. jason-henriksen commented on Jan 15, 2017

    @jason-henriksen

    The API I've been working on looks like this:

    const Foo = styled.div` color:blue; `
    const FooPlus = classed(Foo, `btnClass wavesClass`);
    

    The object "classed" takes the output of styled and inserts a list of interpolated class names that will be appended into className every time FooPlus is used.

    I preferred this API because it leaves the existing API completely un-touched. If you don't want to care about the class names, you don't have to. Even if you're just looking at the code for styled-components itself you could ignore this extension. All the classed() function does is add a classNamesList array to the function returned by styled and then that code inserts the extra classnames if present.

    @geelen : Let me know if you're open to this idea and I'll send you what I have so far.

  24. geelen commented on Jan 15, 2017

    @geelen
    Member

    @jason-henriksen thanks but I think we're going to push forward with attrs (#365) since it solves several other use-cases as well. But there's nothing stopping you from writing classed to call attrs under the hood, if you prefer that API in your own projects 👌

  25. jason-henriksen commented on Jan 15, 2017

    @jason-henriksen

    @geelen #365 makes non-stop rocking possible. Definitely a great way to go that solves this problem in a much more general way.

  26. ticky commented on Jan 16, 2017

    @ticky
    Author

    I actually built basically the same thing earlier in the thread, @jason-henriksen ;P

  27. kitten commented on Apr 19, 2017

    @kitten
    Member

    The attrs, extend and extendWith methods in v2 should totally cover most of the concerns here, if I'm not mistaken?

  28. chhuang commented on Jun 7, 2017

    @chhuang

    For anyone that are not sure how to use these methods and are looking for docs:

    • attrs
    • extend
    • extendWith couldn't find any documentation on this
  29. mxstbr commented on Jun 7, 2017

    @mxstbr
    Member

    extendWith was renamed to withComponent! 😊

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions