Mister Epic
Mister Epic

Reputation: 16743

Read in class names from stylesheet

I've been following along with a React starter kit, and stumbled upon the following:

import React from 'react'
import DuckImage from '../assets/Duck.jpg'
import classes from './HomeView.scss'

export const HomeView = () => (
  <div>
    <h4>Welcome!</h4>
    <img
      alt='This is a duck, because Redux!'
      className={classes.duck}
      src={DuckImage} />
  </div>
)

There is a duck class in the SCSS file, and somehow that's getting read in and assigned as a property of the classes object. Cool! Anyone know how that's being done? I went through the package.json and couldn't figure out the library/tool that was making this happen.

Upvotes: 0

Views: 79

Answers (2)

Pranesh Ravi
Pranesh Ravi

Reputation: 19123

This is straight forward.

All the classes in your SCSS will be converted into style objects. Each class will a property in that style object. This property will carry the information about className and the style.

So when you do

import classes from './HomeView.scss'

the css-loader and the sass-loader will read the HomeView.scss file and convert them into style object. Once this is done, the style object will be exported which is consumed and assigned to classes.

Now, when you do

classes.duck

the class name of the property duck will be returned.

If you try console.log(classes), you'll see all the classes from the scss file.

Hope this helps!

Upvotes: 1

Badr
Badr

Reputation: 10658

Please look at https://github.com/jtangelder/sass-loader

This is the sass loader to load classes

"sass-loader": "^4.0.0",

Upvotes: 0

Related Questions