Repository navigation
Description
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?
- Plus it looks like the use of PostCSS may be impermanent?
Partly adapted from a brief, hit-and-run discussion in the Styled Components gitter 😜
Activity
ticky commentedon Dec 5, 2016
Bonus round: CSS technology soup;
geelen commentedon Dec 6, 2016
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
@composesis tricky. We support nesting in SC but@composescan't work within nested components, so we'll have the same logical inconsistency that CSS Modules suffers, wherecomposes:works mostly like@extendin 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:
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 :)
Semantically, that makes more sense to me, because
styled(x)means you're styling anx. And it's kinda ok that thatxhas classes already attached. But it's a bit of a weird mashup of syntaxes.What do you think?
ticky commentedon Dec 6, 2016
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
composeobject 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?
Leveraging the second argument means you could, ostensibly, keep your shortcut functions very simple - you’d probably be able to just use
bindto make this simple, in fact…geelen commentedon Dec 6, 2016
Hmm, the second argument thing I'm not so keen on. But this kinda would work:
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
classesjust 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 :)smeijer commentedon Dec 6, 2016
I would suggest naming the method
classNameinstead ofclasses, to be more in line withreact.But if you're going with this, I would also suggest a
styleorcssmethod, just for synthetic suger:geelen commentedon Dec 6, 2016
Whoa, very interesting! I only picked
classesbecause 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, theclassNameprop 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:
This sits kinda well with me as a flexible way to attach extra configuration to a component as it's created. The
displayNameandidentifierstuff is gonna be injected by the babel transform, btw, so don't worry about that, so onlyclasses|classNamesandcss|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.
ticky commentedon Dec 6, 2016
This sounds like a pretty promising compromise! Would this make calling
.cssmandatory or would it be skippable at the top (styled.h1orstyled('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;
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” 😜
geelen commentedon Dec 7, 2016
The
.csswould 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.codepunkt commentedon Dec 9, 2016
To be honest, i don't see the benefit here. Imho,
styled-componentsmain 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:Isn't this already possible and fine as is?
ticky commentedon Dec 9, 2016
@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.
codepunkt commentedon Dec 10, 2016
@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?
ticky commentedon Dec 12, 2016
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.
geelen commentedon Dec 13, 2016
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:
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:
But a proper
classesmethod (or some custom interpolation) does. So... I think we should add it. It also has implications for #227 (which currently implementsclassesbut @mxstbr doesn't like the syntax yet 🙃)Any other API options I'm missing?
k15a commentedon Dec 13, 2016
Another API would probably:
IMO this doesn't look as clean as your approach but is a more React style (propTypes, defaultProps)
30 remaining items
xcoderzach commentedon Jan 14, 2017
it should be straight forward to implement, here's an example of how you might do it.
jason-henriksen commentedon Jan 14, 2017
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.
vdanchenkov commentedon Jan 14, 2017
Looks interesting, but I want to mention that it will be harder to detect that
MyDisableButtonis a styled-component in a plugin. IfMyButtonis imported from another file the only way to detect is to analyze contents of template literal and I would not rely on it.xcoderzach commentedon Jan 14, 2017
@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.
geelen commentedon Jan 14, 2017
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):
This api is totally fine though:
So much cleaner!
ticky commentedon Jan 15, 2017
Doesn’t the existing infrastructure pretty handily support style composition anyway?
geelen commentedon Jan 15, 2017
Yeah we're ditching that for consistency. If you call
styled(X)you should always get a component that wrapsXand passesclassNameto itjason-henriksen commentedon Jan 15, 2017
The API I've been working on looks like this:
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.
geelen commentedon Jan 15, 2017
@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 writingclassedto callattrsunder the hood, if you prefer that API in your own projects 👌jason-henriksen commentedon Jan 15, 2017
@geelen #365 makes non-stop rocking possible. Definitely a great way to go that solves this problem in a much more general way.
ticky commentedon Jan 16, 2017
I actually built basically the same thing earlier in the thread, @jason-henriksen ;P
kitten commentedon Apr 19, 2017
The
attrs,extendandextendWithmethods in v2 should totally cover most of the concerns here, if I'm not mistaken?chhuang commentedon Jun 7, 2017
For anyone that are not sure how to use these methods and are looking for docs:
attrsextendextendWithcouldn't find any documentation on thismxstbr commentedon Jun 7, 2017
extendWithwas renamed towithComponent! 😊