Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add scoped css in react?

Is there a React equivalent of scoped css as in Vue that's super easy to work with, without a bunch of re-writes? One which I can just import an existing css file, and hook it up to a component, and it just works?

In Vue, it's as easy as

<style scoped src="./boxes.css"></style>

And Bam! Your css is now scoped to your component.

Is there anything similar in React? Something like

// import the css file
import styles from "./boxes.css";

// hook it to a component, or using any other methods
@inject(styles)
class Boxes extends Component {
  render(){
    <div className='container'>
       /* must support multiple classes out-of-the-box, unlike CSSModule where you have to 
       re-write into a super long array like className={[styles.box, styles.green, styles.large]} */
      <div className='box green large'></div> 
      <div className='box red small'></div> 
    </div>
  }
}
like image 633
Maria Avatar asked Jun 14 '18 03:06

Maria


People also ask

Is CSS scoped in React?

By default, CSS in React is scoped globally. This means that using the same className for 2 elements will cause a clash. One way to avoid clashes without any additional configuration is to make sure you're using unique class names for every component.

How do I import a CSS module into React?

To import a CSS Module into the corresponding component, import the css modules stylesheet as styles or [name]Styles : In JSX, use the defined CSS class as a className prop like so: From here, you can add as many other CSS modules you'd like, just remember to import each as a different name.

What is the scope of the CSS module for the React?

In the React application, we usually create a single . css file and import it to the main file so the CSS will be applied to all the components. But using CSS modules helps to create separate CSS files for each component and is local to that particular file and avoids class name collision.

Can you add CSS to React?

You can create a new CSS file in your project directory and add your CSS inside it. You can then import it in your component, class or React JS page.


1 Answers

Every answer here is about CSS Modules, but scoped styles in Vue works another way.

Here the library for React that works like <style scoped> in Vue: https://github.com/gaoxiaoliangz/react-scoped-css

Input:

import React from 'react'
import './Title.scoped.css'

const Title = props => {
  return (
    <h1 className="title">
      <p>{props.children}</p>
    </h1>
  )
}

export default Title

Output:

<h1 class="title" data-v-hi7yyhx>
.title[data-v-hi7yyhx] {}
like image 67
Даниил Пронин Avatar answered Oct 01 '22 18:10

Даниил Пронин