Scoping CSS in React


#1

Hello everyone,

I try to scope CSS in React the same way that it is done in Vue.

I believe this is the way to go. Another way I found but I have no clue how to integrate with Meteor either is this one: https://github.com/gajus/babel-plugin-react-css-modules
but it relies on Webpack as well.

In Meteor, without webpack I’d probably need to rely on babel and postcss? I have no clue how to integrate these together.

@akryum as you did port vue-loader from webpack to meteor, do you have an idea of what is needed to have the same thing in React?

Basically I would declare my styles in the middle of a .js file like that:

or and this would work similarly to how vue is doing. @all: how do you manage your styles in React today ? BEM convention? or you have something more solid like Vue?

#2

Using styled-components:


#3

Ideally I would not introduce too much special syntax. the backquote is not a key on french keyboards by the way (and I live there…)


#4

styled-components doesn’t use a special syntax - it’s using tagged template literals, which are part of the ES2015 spec.


#5

How do you go about using the post-css plugins with this solution ? (autoprefixer and other tools)


#6

You can’t use postcss with styled-components. But styled-components do auto prefixing automatically for you. Instead of using postcss plugins you can use javascript functions that do transformations like units convertion etc.


#7

Exactly as @mpowaga said - and if you’re interested, behind the scenes styled-components uses stylis to handle vendor prefixing.


#8

How well do styled component play with other css files ? (my global ones)


#9

Yes it is. French keyboards have the backtick.
Sur la touche è .


#10

Well I would probably prefer just to use normal css syntax. It’s cool to be able to inject javascript in CSS, but it’s not what I want.

I want a simple way to scope CSS but keep writing what seems to be CSS. Preferably like Vue.

Is there anything like vue-loader for React ? Not a big fan of CSS in JS


#11

Been using https://github.com/nathantreid/meteor-css-modules/ for a while, It integrates the postcss implementation of CSS modules into the meteor build process, and it’s working pretty well.

It’s regular CSS modules, so you won’t get JS+CSS in one file like with Vue single-file components.
You put a CSS file next to your js component file, import styles from './MyComponent.css' in your component, and put className={styles.someClass} in your component’s JSX. Voila :slight_smile:


#12

styled-components is also the way to go for me:

  • solves all problems with css and styling
  • uses default css syntax
  • easy to use
  • nice template feature
  • good performance
  • works in react-native as well