React: Really like Vue's solution for css, how about a similar one like this for React?

Created on 16 Jun 2018  路  9Comments  路  Source: facebook/react

Do you want to request a feature or report a bug?
feature

What is the expected behavior?
So I really like Vue's solution for css, how about a similar one like this for React?

// App.js
import Scoped from "scoped-css"
import style from "./App.css"

const App = () =>
<Scoped style={style}>
   <div className="App">
        <div className="header">
          <h2>Welcome to React</h2>
        </div>
        <p className="intro">
          To get started...
        </p>
      </div>
</Scoped>

//App.css
.App { ... }
.header { ... }
.intro { ... }

CSS will apply to elements of the current component only, and parent component's styles will not leak into child components.

Most helpful comment

I think that styled-jsx and CSS Modules already achieve what you're thinking of.

All 9 comments

I think that styled-jsx and CSS Modules already achieve what you're thinking of.

Or Aesthetic if you prefer a css-in-js approach (self-plug): https://github.com/milesj/aesthetic

JSS is a nice CSS-in-JS option, used by the guys behind the material-ui react library

http://cssinjs.org

Needless to say, take your pick of solutions. This is not a React issue :)

The Vue approach is a bit different and would actually need some kind of internal support to work, but it's probably nothing that a Babel transform cannot do.

Basically, they add a data-{somehash} key to every single DOM element that is directly generated from the <template> in a file that has a <style>. The classes in the <style> are modified to require that [data-{somehash}] attribute to be present to match.

As far as I know this is not recursive and will not affect the DOM elements generated by other components; if it were, it would only be implementable in core.

Thanks everyone for replying with helpful resources!

If there's a change to React that you think would improve styling, please consider filing a proposal at the React RFCs repo. In the mean time, I'll close this out.

This could be a little challenging to implement.
it will be great if it is something like this,
restricted import './style.css' in Component.js.
All the class names in the dom also being virtually named with a scope in reference.

Is there currently no solution that allows global and scoped styles to be applied? Vue just adds a data- attribute and leaves the classname untouched. Scoping the classname by modifying it destroys the ability to use global styles (like grids, etc.).

I've just found https://kremling.js.org
IMO it seems be the most Vue-like lib for react as css can be scoped and placed inside jsx (without external .css file)

Maybe it will be usefull for someone..

Edit: there's also VSC hightligher https://github.com/geoctrl/vscode-kremling but I'm missing Intelisense here.

Was this page helpful?
0 / 5 - 0 ratings