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>
}
}
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.
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.
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.
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.
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] {}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With