Re:Show HN: Single-file components for React
by akawry on Thursday October 05, 2017 @02:02PM
(#15411175)
What about just importing the css file from your component file?
For example, in MyComponent.js, you have:
import './MyComponent.css';
const MyComponent = () => (
<div className="my-class">I'm a component!</div>
);
and in MyComponent.css, .my-class {
color: red;
}
To handle proper scoping, you could use something like css-modules or wrap each component in a top-level <div> with a component-specific class name. For example: const MyComponent = () => (
<div className="MyComponent">
<div className="content">
I'm a component
</div>
</div>
);
and then .MyComponent.content {
color: red;
}
If you use a preprocessor like sass, you can just nest your entire component-specific styles like this: .MyComponent
.content
color: red
.footer
color: blue
Thanks for your feedback!
I guess you mean CSS-in-JS approaches where CSS is either put inside JS code as a template literals/string (styled-components, csjs etc) or as inline styles with JS objects (Radium etc.). Both approaches have their own advantages and disadvantages.
It could be only me, but I personally don't like the idea of having inline styles, although I realise it could be the only way to make styles cross-platform.
The string approach works well and has additional advantage of dynamic property values (in case of template literals). However, (and this is IMHO again), I can't say this is the most readable way to structure code, especially if you rely on IDE/text editor identifying this code as CSS.
There is a third approach, which is basically putting <style> tag right in JSX component, but this then gets repeated with every component you put on the page. Thus, I wouldn't consider this as an approach at all.
Let me know if I missed anything above.
My initial intention was to create a way to get styling and JS/JSX code together in one file in a way that would keep code readable and reusable.
This experiment does not tick all the boxes for the cross-platform, easy to write and read reusable way of combining styles and JS code in one file. However, the concept could be convenient in some cases where cross-platform-ness is not a requirement and styles are already written in CSS.
As I mentioned, one-loader was inspired by vue-loader, which I found convenient for the purpose of storing css and js code in one file.
Hope that makes sense