
Re: “‬How does writing CSS in JS make it any more maintainable?” - playpause
https://gist.github.com/threepointone/731b0c47e78d8350ae4e105c1a83867d
======
aphextron
Having tried every alternative imaginable, component based CSS is the way to
go. There's a legacy in web development of viewing CSS as something separate
from structure and logic because of what the web used to be; a collection of
static pages with style sheets for typography and layout. But as soon as you
start building any kind of non-trivial application, this model breaks down.
The only way to do it is small, atomic, composable components with fully self
contained styles and minimal inheritance.

~~~
weberc2
Could you elaborate on what component-based CSS is for the uninformed? A
cursory Google search indicates that it's a technique for using CSS in JS, but
I'm not sure how I would go about doing it. Does it imply some web component
framework?

~~~
aphextron
>Does it imply some web component framework?

Not particularly. You can use pretty much any modern framework, they are all
using a component based architecture for the most part. Vue, React, Polymer,
even native web components are usable now. Here's an example of how Ember does
it:

[https://github.com/ebryn/ember-component-css](https://github.com/ebryn/ember-
component-css)

It's just about breaking down your pages and views into small components which
can be reused and maintained separately. Instead of having one giant
stylesheet with a deep inheritance of cascading classes, you just have a a
bunch of components that are imported and namespaced by the compiler. That
extra layer of abstraction gives you the ability to organize your project in a
way that isn't beholden to the specific quirks of CSS, and removes the mental
burden of things like SMACSS from the developer.

~~~
vanadium
This is easily done using SASS components as well. No framework needed.

~~~
kakarot
It depends on how you want to structure your app.

If you want all stylesheets living under src/stylesheets or if you would
rather have them each live inside a component folder.

The latter allows for better portability of components but you generally will
need a build system.

~~~
vanadium
All of our components are contained in a folder specific to that component,
and include the JS (Vanilla ES6), SASS, and template markup.

------
ex3ndr
CSS in JS turned into a nightmare in our project once we decided to make it
fast. CSS in JS usually do next things for each component mount:

1) Parse CSS

2) Hash styles object

3) Serizlize and auto-prefix CSS back (or just write to StyleSheets API)

That is actually a nightmare for performance. You can say that you can export
static styles via babel and everything will be fast again (since 90% of your
styles are static), but styled-components, glamorous, emotion and friends all
ditched static styles exporting feature.

On the other side we thought that composing styles is a good thing, but it
turns out to a complete mess where you have 100s of style overrides across the
code instead of building a small component with appropriate API.

On the last side i personally came from mobile world. Most of mobile (native)
devs tried to build their own "css" or manage styles in some "special" way
that it used to be (constants in some static class). It turns out it adds
almost zero profits and too much of maintenance. They are not helping you to
simplify things if you wish to change something "everywhere" beside very
simple things (dividers, borders, backgrounds, tint color) and everything is
just became useless. Building real components is much much better.

Well, considering all this we have only one (!) CSS in JS library that satisfy
this requirement:
[https://github.com/jsxstyle/jsxstyle](https://github.com/jsxstyle/jsxstyle)

It is fast, performant and completely static if it possible but it is not
"fancy" in frontend community. As usual in frontend there are not much sense
everywhere and popular libraries are usually a complete crap if you really
value your users.

~~~
vcarl
We've not run into any performance issues in our 80k LoC JS app using styled
components 100%. I'm not sure it's accurate to say it's ditched static styles
exporting, with babel-plugin-styled-components we're getting a handful of
style tags on the page that are generated at build time.

~~~
ex3ndr
Not sure about your stack, but styled-components declared it as deprecated and
babel-plugin-styled-components page doesn't show anything about static style
extractions.

I think it depends on your requirements, we have a messaging app and i need to
switch chats in < 30ms without caching of pages. Otherwise page will be junky
for non-chrome browsers.

~~~
vcarl
Not sure where you're getting that it's deprecated. Both the repo itself and
the styled components website list it as a highly recommended (but optional)
addition.

[https://www.styled-components.com/docs/tooling#babel-
plugin](https://www.styled-components.com/docs/tooling#babel-plugin)

~~~
ex3ndr
Plugin is not deprecated, sure, but it doesn't do static style extraction:

`This plugin adds support for server-side rendering, minification of styles,
and a nicer debugging experience.`

------
quantummkv
So we have gone back to the days of Java and WinForms where everything from
the UI layout to styles to business logic was in the same damn language in the
same damn file and many times in the same goddamn function.

Why? Why in the world would you ever willingly want to go back to that? Has
the JavaScript community collectively lost it's mind? Or has all that kool-aid
gone to its head and everyone is under the impression that they can do no
wrong? What happened to all that talk and bluster that Java and JavaScript are
different?

Even .Net and Java have moved away from that convention with XAML and JavaFX.

Those who don't remember the past are condemned to repeat it. My only hope is
that the JavaScript community comes to it's senses before it is too late and
they take down a good language and platform because of their inability to look
outside the bubble.

~~~
tracker1
It's not quite the same... styling conventions can still be followed,
inherited style structures can also be passed from a global theme, or higher
order components. You get the added advantages of a more flexible
configuration that more easily integrates with the rest of the application as
a whole.

When developing a website with mostly static or cms type content, it's fine to
establish a common layout structure that targets css output like sass, less,
pre/postcss etc.

When developing an application with components, it's generally best for
component styling to stay closer to the component. CIJ is simply an option
that works very well with all the advantages of per-component styling. But
over separate .scss files has the added advantage of easily injected
runtime/configuration values. It's much harder to generate different global
values for $primaryColor and related in scss for different deployment targets.
More so if you want to swap out themes, or certain options via application
configuration in the application.

~~~
quantummkv
> inherited style structures can also be passed from a global theme, or higher
> order components.

Correct me if I am wrong, but isn't this the whole point of _Cascading_ Style
Sheets?

> It's much harder to generate different global values for $primaryColor and
> related in scss for different deployment targets. More so if you want to
> swap out themes, or certain options via application configuration in the
> application.

Isn't this exact problem solved by custom css properties/css variables? Why
recreate CSS in JavaScript with all of the compile-time and run-time overhead
when you can write a small function to manipulate css variables?

~~~
tracker1
Okay, so you want a global setting for buttons...

    
    
        button {...}
    

Now you have a component where there's a variation on the button...

    
    
        .foo button {...}
    

Now you want all buttons to have that variation...

    
    
        button {...new...}
    

Now you change button defaults...

    
    
        button {...new...}
    

Oh crap, `.foo button` is broken.

------
rglover
As a former purist who's adopted the styled-components implementation of CSS-
in-JS, I can say 100% that maintaining styles has become _an absolute dream_.
It's not terribly different from CSS (meaning, if you need to extract a
stylesheet it's just a few lines of code) and its ability to do autoprefixing
and Sass-style nesting out of the box is a massive time saver. Coupled with
CSS variables, it's an ideal toolset for authoring styles.

I've spent over a decade fighting with CSS. Sass was a welcome upgrade. CSS-
in-JS is a welcome next step.

~~~
jf-
What's the advantage to this over sass modules? You have the same scoping but
with better separation of concerns, that seems the superior choice.

~~~
silviogutierrez
I used to think this way. In reality, you're not separating concerns, you're
separating technologies (CSS and HTML).

Should your backend authentication code live in the same file as your billing
logic? Probably not. Separate concerns.

But when the concern is "a sign up component's look and feel", I see nothing
wrong (anymore!) with lumping it together. In fact, I prefer it. Just my two
cents.

~~~
jf-
Logic, layout and style are inherently separate parts of a component. Separate
concerns in other words. Ideally they should have separate definitions. This
is the cleanest and most maintainable structure.

The cycle seems to be to separate things clearly, then mix them back again,
then separate them out again. I’ll happily skip the mixing part of this cycle.

However, that said I don’t want to give the impression that I’m being
proscriptive here, other developers are perfectly free to have their own
preferences just as I have mine.

------
tboyd47
> Further, it’s extremely hard to statically analyse selectors to see whether
> any rules are broken (or even a typo!) this means constraints have to be
> enforced via code reviews and education, which is a harder problem to solve
> and scale. We should use a computer's assistance us on this, and not rely on
> humans being infallible (they’re not!)

Is there a more general name for the argument in defense of a technological
movement on the grounds that it prevents users of said tool from making a
certain mistake, and that mistake is so disastrous that we see it necessary to
implement a drastic change with wide-ranging demands on an entire class of
users or eliminates them entirely from the user base?

I see this kind of argument prop up all the time in these types of discussions
and something about it just fundamentally irks me, but I can't put my finger
on it. It's kind of like Google's AMP, where instead of making incremental
changes to the technologies in question, we'd rather draw an arbitrary line
between "good" and "bad" uses of that technology and create a fork or subset
of that tech where only the "good" uses are allowed.

For a less controversial but equally relevant example, see Crockford's
"Javascript: the Good Parts," which irked me at the time as well for the same
reasons, even though it became universally accepted (although not-so-
universally applied).

I'm trying to come up with an example from my favorite language (Ruby) and I
can't. Ruby's approach seems to be to discourage "bad" use cases by making
them ugly (ex. instance_variable_get) rather than preventing them outright.

------
iooi
I use CSS modules coupled with postcss (mainly for minimization and
autoprefixing) and sass-loader almost exclusively. The one benefit from CSS-
in-JS I can think of is when the JS needs to know of a value that would
otherwise exist in CSS only.

For example, I'll usually have a constants.scss file that I @import in other
files, which for example will have a $max-modal-width: 600px;

I have run across use cases where I want to read that value from JS, but I
could never figure out how to do that and resorted to duplicating the
constant's value in my code. CSS-in-JS would make this trivial.

~~~
Chyzwar
You can use CSS Variables to bridge between.

    
    
       var style = getComputedStyle(document.body);
       console.log(style.getPropertyValue('--color-font-general'));
       :root { --color-font-general: #336699; }
    

As a bonus point, you can also change the values of CSS Variables and layout
will update automatically. Take a closer look at styles of YouTube.

~~~
tracker1
Seems like a rather ugly hack to reverse-render values out.

~~~
Chyzwar
CSS Variables seems to be very useful for CSS. I am not sure if changing
dynamically CSS variables from JS is a great idea but you have options to do
so.

There is more coming in project Houdini.
[https://developers.google.com/web/updates/2016/05/houdini#th...](https://developers.google.com/web/updates/2016/05/houdini#the_specifications)

------
btown
I strongly disagree with the CSS in JS movement, because philosophically it
gives _false hope_ about isolation. The thing is, no matter how you try to
isolate a scope, things are going to cascade! You could have someone above you
change the font weight and not visually QA all your code paths, and now your
subcomponent's entire layout could be messed up. BEM, SCSS, and standardized
namespacing get you 90% of the way there, and force you to think about the
cascade when writing.

~~~
gambler
I disagree with it for another reason. I'm tired of developers solving
_language design problems_ by piling on more and more complexity, tools and
libraries. This is a self-defeating approach, because those tools and
libraries often have their own issues, and instead of fixing _those_ , people
pile on even more tools and libraries. The process goes on and on. It may feel
like progress, but it doesn't really go anywhere.

Java was a good example of this. Instead of fixing core language issues,
people used increasingly sophisticated IDEs and put more and more things into
XML. Instead of adding essential functionality to the standard library,
everyone said "just download this great third-party JAR". At the time Java
community said the workarounds were good enough. Right now it's obvious that
they were completely wrong, the pileup of complex tools wasn't sustainable and
that the language itself needed improvements.

~~~
tracker1
The DOM has styling primatives... many CSS in JS libraries use them... others
compute CSS from the JS object structure used to define (based on JS DOM
interfaces for styles).

------
danShumway
One major problem I've run into is that CSS in JS usually lacks support for
pseudo-classes and browser breakpoints.

The recommendation from communities in frameworks like React is that you
should use JS and extra elements to polyfill that behavior. This is both less
performant and less semantic. It really doesn't work particularly well if
you're used to leveraging CSS in powerful ways.

Stuff like :first-of-type, sibling selectors, and so on are extremely useful.
You give them up when you start manually attaching inline styles, and both JS
performance and JS complexity to replicate those features will pretty much
always be worse.

Doing animations in JS is usually a step too far even for the React community,
so the recommendation I see there is often that you should define normal CSS
classes and dynamically apply them. But now you're starting to mix CSS and
CSS-in-JS, which is do-able, but can come with own set of subtle consequences.
It also significantly lessens the benefit of CSS-in-JS, which is that you get
to stop worrying about conflicts. It's not a dealbreaker, but it means you're
somewhat back to managing the same name conflicts and typos that you were
before.

I started out as much more open to CSS in JS than I am now. I was cautious
about it and usually avoided it for personal projects. After doing a little
bit more work on projects that use this pattern, I now feel like it's
_probably_ a bad idea, and advise other people to be careful about using it,
even if I'm not willing to take a hard stance quite yet.

It's not that component-based CSS is a bad idea, I'm much more friendly now
towards BEM than I used to be. And it's not even that CSS outside of JS
doesn't have problems (the authors point about loading order is a particularly
good example, albeit one that really shouldn't be coming up very often in a
component based world. Also yeah, testing). I'm just less convinced that CSS
in JS is a sufficiently scalable solution to those problems, or that it
doesn't have significant problems of its own.

~~~
Cu3PO42
I think you're missing an important point. Not all CSS in JS solutions attach
styles as inline styles. Some of them, such as Styled Components [1] and
Emotion [2] (and many more) will actually generate proper CSS Stylesheets and
attach them to the document, thereby enabling usage of all CSS
features—including, for example, pseudo-classes.

This may incur some additional runtime cost when the page loads (which is
definitely nothing to dismiss), but should be (roughly) as performant as
"native" styles after.

They still come with other disadvantages (and advantages), so I'm not saying
you should definitely use them, but maybe you should take a look at some
implementations you might not have seen yet.

Personally I arrived at the conclusion that they're not for me and that I'll
just stick to SCSS.

[1] [https://www.styled-components.com](https://www.styled-components.com)

[2] [https://emotion.sh](https://emotion.sh)

~~~
danShumway
You're right, I didn't know that there were solutions that took this approach!

Yeah, I would agree that dynamically attaching stylesheets is better than
using the default React model for inline styles. I'd still be worried about
the performance implications, but this might address a lot of my concerns.

------
tracker1
Regarding most of the dismissive comments on using JS for styling...

1\. you can't inherit... 2\. I don't want it in the same file...

    
    
        // component.style.js
        import base from '../base.style.js';\
    
        export style = theme => ({
          ...theme.typography.body1,
          ...base.component.foo
          fontFamily: theme.fonts.serif,
        });
    
        // component.js
        import { style } from './component.style';
    
        ...
    

I'll see your objections, and raise you one...

    
    
        // theme-builder.js
        import deepMerge ...
        import { get } from './api-client';
    
        export default async _ => {
          const [base, client, application, user] = await Promise.all([
            get('/styles/default'),     // default options
            get('/styles/site'),        // client/deployment options
            get('/styles/application'), // in-application configured options
            get('/styles/user'),        // in-application user options
          ]);
          return deepMerge(base, client, application, user);
        };
    

I'm currently working on an application that has those needs... doing that
per-user means building styles at the server every time... using JSS, I just
deepMerge some JSON/Objects and it all _just works_. I've built applications
both ways, BEM, generated selector replacement, other techniques, and JSS...
I'll take JSS.

------
janpot
Pure the use of JS vs. CSS is not what makes CSS-in-js more maintainable. It's
"scoping styles locally to a component" that makes it more maintainable. As
well as having easier interaction between them, like theming or dynamic
behavior.

------
vinceguidry
It doesn't. But what it can encourage you to do is to stop writing CSS that
has effects outside of the component it's attached to.

Devs doing front-end have this tendency to treat styling a page as some
unsavory thing that they want off their plate as soon as possible. So they
don't do any refactoring, and don't take any time to try to figure out the
underlying concepts behind CSS. So you get these giant, append-only
stylesheets that have no real rhyme or reason behind them.

Putting CSS in your JS has the side effect of hopefully forcing you to think
more carefully about what rules go where. It's no magic bullet of course, but
localizing all the code to one component in one file can make everything just
a slight bit more maintainable.

There are real tradeoffs, of course. CSS in JS just isn't as mature as
existing template solutions, and they don't yet let you do anything you want
with them. Maybe it's a good thing.

~~~
exogen
While that is a benefit, I think that's underselling it a bit. It certainly
enforces more organization & discipline, but some benefits are more concrete
and technical. :)

For example: sending down only the critical styles needed to render a page.
Many CSS-in-JS approaches get you this for free. If a component isn't rendered
on the page, its CSS isn't on the page either. That can be technically
challenging even if you follow the strictest, most disciplined patterns when
writing your CSS in a traditional way.

Another is guaranteeing no naming clashes. You could be extremely disciplined,
but let's say there are 80 developers working on different parts of your large
site/application. How are they going to know that some other developer in
another group isn't adding selectors for another component with the same name,
even if it's a very specific name and follows best practices? Solutions that
mangle the class names to guarantee uniqueness automatically fix this.

There are more, but those two come to mind immediately.

~~~
vinceguidry
Agreed, thanks for elucidating.

------
matte_black
I find that the people with the most vitriol reserved for css-in-js concepts
tend to be those who have exclusively developed front ends for the web and
never on any other platform. I wonder if others have made the same
observation. Perhaps they should expand their minds.

~~~
andrewmcwatters
The alternative is imperative UI design à la Win32, so I'm not sure what
there's to expand on. Unless you really think writing a couple hundred lines
of code to set position and apply event callbacks is a good idea.

------
gambler
Moving CSS to JS because of selectors? Hm, I often do the exact opposite. I
effectively move JavaScript logic into CSS queries and data into corresponding
tags/attributes. When I started doing that, my scripts became far more
enjoyable to write, trivial to reuse across projects and orders of magnitude
easier to analyze/debug (just run the query and see what it finds, mostly).

All things considered, CSS is a pretty good language. Selectors are a great
query language, as long as your tags have well-expressed information.

CSS definitely needs something to address specificity, though. Maybe HTML
needs an explicit tag or attribute to denote context, so that styles from
higher level contexts would not apply to nested contexts. Purely from syntax
perspective this could be addressed in CSS queries themselves, but I doubt
such implementations would be efficient.

Another things CSS needs is some way to analyze it from scripts. It's amazing
that there is no way to query/modify CSS rules from JS. It would solve so many
issues with very little client-side code. You could _implement_ CSS variables,
for example.

I'm talking about interacting with actual styles. E.g.

    
    
        let x = CSS.forSelector('article p').getRule('font-weight');
    

or maybe:

    
    
        let x = CSS.activeRules['article p']['font-weight'];
    
        CSS.forSelector('article p').setRule('font-weight', '10'p);
    

You can fake the last one by dynamically generating CSS on the page, but that
approach has many issues that would be avoided if there was a clean
programmatic interface.

With an API like this you could trivially post-process styles, extend core CSS
functionality and even do some cool runtime analysis, like finding which rules
aren't used on a page.

\---

General CSS note. One thing I advise everyone to try is getting rid of any BEM
classes for your components and replacing them with custom attributes. The
idea is that each component (block in BEM) gets its own attribute and all the
elements and modifiers go inside that attribute.

So instead of BEM

    
    
        <div class="block__element block__element--modifier">
    

you get this:

    
    
       <div a-block="element modifier">
    

or this:

    
    
       <div a-block="element-modifier">
    

(By convention, custom attributes should always have dashes, so you never run
into conflicts with core HTML standards and so that everyone can tell they're
custom from the first glance. I never thought I would miss XML namespaces, but
they sure would come in handy here.)

Not only it's shorter and nicer to look at, it expresses more useful
information and can be queried in ways that's impossible with BEM.

To use this, you need to be aware of the following CSS selectors:

    
    
        [attr~=val]
        [attr|=val]

~~~
apineda
What about performance when relying so heavily on this string matching with
attribute selectors.

~~~
gambler
What about it?

Personally, I haven't run into any real issues with performance using advanced
CSS selectors. But as with any performance statements, this applies to HTML,
CSS and JS I worked with, on the browsers I tested with.

------
jpochtar
In about 5 years, we're all going to be on inline styles in JSX (or
equivalent), flabbergasted that we ever thought CSS was a good idea. Calling
it now.

------
AchieveLife
Next on HN: Why Javascript is the future of voting machines

------
coding123
Css is a write only language. There is no read mode.

~~~
wvenable
You can read it the browser using the developer tools; 99% of my reading of
CSS comes from there. I add/tweak in the browser and then I go to the source
and re-apply the changes there.

------
InGodsName
Is scoped CSS different from CSS in Js?

Sorry for the noob question.

~~~
tracker1
Yes, all CSS operates via selectors... scoping generally means applying a
className to a component, and then generating all CSS for children relative to
that. The issue at play is when you start nesting, or using components
together, and child naming blows up.

    
    
      .myComponent
    

is fine... but when you have:

    
    
      .myComponent button { ... }
      .myComponent .x
    

and then you have conflicting rules, and your css gets overridden in
unexpected ways. with JSS, the tooling can generate unique component
selectors, and since it's all generated at a component level, you have less
risk of applying conflicts.

------
threepointone
How do I blacklist my own urls from this website?

------
dccoolgai
Short answer: It doesn't unless you follow some light "Design by Contract"
principles... unfortunately that flavor never really caught on.

------
preommr
Honestly, what the hell are we talking about here?

CSS is one thing and JS another.

It's typically better to use CSS for styling because it's declarative and
simple. If your use cases are more complicated then use css preprocessors to
resolve issues like variable names (something brought up in that twitter
convo). If you want to do things at runtime then you need something procedural
like js.

If you decide to forego css even for simple cases and use js because you think
it'll be easier to maintain then obviously you'll need some tooling and
conventions in place. If you have those, go for it.

If people want to put js in css (again, something brought up in the twitter
thread), then that's fine too if various vendors supported it and there was a
reason for it over js. There currently isn't, so again, I don't know what the
hell we're talking about.

Also:

> The facebook codebase has thousands of !important statements, despite being
> _written by competent engineers with solid engineering practices and deep
> relationships with design teams._

lol

~~~
danabramov
_> lol_

"I'd rather assume other people are incompetent than accept that maybe
maintaining tens of thousands of components presents unique challenges that I
could learn from."

~~~
preommr
lol because it's a meaningless statement not the least because it implies
smart people always produce perfect code.

I don't think it's ever a good idea to bring into question people's competency
when discussing software design principles. It's hard to quantify, difficult
to verify and not usually relevant.

I am not assuming they're incompetent. I am disagreeing with the idea that
their failure comes from just the technology and not in anyway from the
actions of a developer. Whether it's because time constraints or just because
shitty things happen like they do in any project regardless of how much money
or how top tier the talent is.

~~~
andrewmcwatters
> "I'd rather assume other people are incompetent than accept that maybe
> maintaining tens of thousands of components presents unique challenges that
> I could learn from."

Entirely disingenuous, and doesn't assume good faith by communicating
experience.

> I am disagreeing with the idea that their failure comes from just the
> technology and not in anyway from the actions of a developer.

Exactly. More often than not, in fact a majority of the time, people are
flawed when it comes to UI development. This underscores how greatly we
undervalue good engineering. It's not some thing that's just commonplace.

As a barometer, not all of my coworkers are competent enough to build projects
or products on their own that other engineers want to consume. In fact,
especially when it comes to UI-related projects, almost none of them are
competent enough to do so, and that's okay.

But it means I extend this criticism outside of the workplace, where I've
worked at several companies where people could hardly take Photoshop renders
and accurately replicate them in HTML and CSS, nor did many of them have an
appropriate grasp of the visual formatting model.

------
andrewmcwatters
I'm always curious about what the largest magnitude of a UI codebase someone
has maintained when they make comments like this.

~~~
tracker1
I'd like to see you maintain a codebase of thousands of components with CSS in
JS vs another management solution via CSS build (like scss) and see how many
buggy/hacky issues you have with each. I've worked in codebases of significant
size managed both ways.

If you want the most simple example, look at most apps based on bootstrap.
They only start with the baseline/generated CSS, then apply hack patches
throughout an application. Yes, you _should_ use the source and generate
yourself, for your application. But nobody does in practice. Even worse, a lot
of the "bootstrap components" from third parties are also using hack css on
top of the baseline, and require even more patches in actual structure.

I'm not bashing bootstrap, only pointing out how I've seen it used, which is
poorly. Component based CSS in JS has even been a bit of an issue. Other
developers on my team will put magic values into a given component instead of
using values out of the theme that gets injected. I've had to go through again
and again to correct this.

The difference is the former yields unexpected behaviors, while the latter is
just a bit of inconvenience.

~~~
andrewmcwatters
Uh, bullshit? Thousands of components? Yeah, okay. You create a single new
component for every permutation, route, and derivation? Where are these
projects with thousands of components? What open-source projects can we use
for reference? Are they all commercial and therefore private? That'd be
convenient wouldn't it? Bootstrap lists 21 individual ones, not counting
layout, content, utilities, or other classes.

Lets say you have a SaaS project with a couple hundred individual routes, and
you count them as individual components, you still haven't reached the
magnitude you're talking about.

~~~
tracker1
I separate a lot of if/else components into a logical component and a render
component. Now only the render components have styling, but they can share
common style configuration, usually through a theme that's injected higher up
(react-jss).

This keeps complexity of render components relatively smaller. I also don't
mind breaking up compositional components for say NumbericInput, IntegerInput,
WholePositiveInput, WholeInput, etc for form fields, each one with some entry
filters in the component, and state level validation elevated to the
containing component (and ultimately through form events, etc).

Beyond a lot of this, you have components with some display variances
(subheaders that are shared in a given section of an application for sub-
navigation, and some informative display), Most displays in the application
I'm currently working on have about 5 shared higher order components (route
level, header, section subheader, page footer, page capture/composition, data
rendering, form input), and about 10-15 smaller/nested components just for
rendering about half shared.

Across the application so far, there are about 200 components, with the
application about 30% complete. The application itself is using react-jss as
it's the base for styling with the material-ui component library. I've tweaked
what gets placed in the theme a bit to pass additional configuration items
into the theme. Portions of these additional options are part of a release
configuration (per client environment/deployment), and part from flexible
application options that are loaded from the API when the application loads,
configurable within the application.

I've done similar things with dynamically generating base.scss files, and
frankly the CSS-in-JS is far more predictable and easier to manage compared to
prior applications using Bootstrap or similar SCSS/Less component baselines.

------
weego
"In an SPA/component world, where assets like scripts and styles are loaded
asynchronously, you can’t guarantee style sheet loading order, which means you
have to lean on some form of runtime composition to guarantee a shape, else
you end up with !important rules even if you follow a given architecture"

I'm sorry, this guy is so far down the rabbit hole he can't even see the
ridiculousness of his mental gymnastics.

~~~
whyonearth
The thread makes me want to quit the industry. One person disagrees and gets
"I vote for this statement to be nominated for Worst Sentiment of 2018", while
the gist-er is congratulated with "instant classic" and "you're my hero." The
JS cargo-culting insanity is becoming unbearable and dissenters are mocked as
noobs.

~~~
icholy
Just get off the front end. Things are pretty sane everywhere else.

~~~
rjplatte
Agree. I'm trying to right now. I think it has more artsy types, which means
more drama.

~~~
strken
I think it's because SPA web development is like using a hammer made of
chewing gum to build a house, and the ridiculous toolchains necessary to build
a solid hammer always look complicated and unnecessary.

EDIT: What I mean here is that the foundations of the web weren't designed for
application development and are missing some crucial bits and pieces like
encapsulation. The tooling necessary to encapsulate CSS in a way that works
with every browser is complicated, and if you've only worked on small to
medium projects it can be hard to see the need for such complication.

