Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ClassName styles not working in react

I'm having a little issue with styling react components. I have my scss stylesheets in a separate file and importing them into my react file. My scss stylsheet looks like this:

.testStyle {
  font-family: avenir;
  color: blue;
}

My react file, looks like this:

import React from 'react'

import styles from '../styles/main.scss'

class Temp extends React.Component {
  render() {
    return (
      **<div className={styles.testStyle}>**
        <h1>Hello</h1>
      </div>
    )
  }
}

export default Temp

With this setup, my styles are not passed through, however, if it works if I replace the starred line with <div className='testStyle'>, so it seems like the styles are being imported correctly. Can anyone help with this? Thanks.

like image 572
Pmmoks Avatar asked Oct 07 '16 22:10

Pmmoks


People also ask

Why is my CSS not working in React?

This error is generated because the compiler is only able to import files from the src folder. Here, the CSS file is saved outside the src folder, so the compiler failed to import it. To make this code work, you just have to save the CSS file inside the src folder.

Can we use class instead of className in React?

Explanation: The only reason behind the fact that it uses className over class is that the class is a reserved keyword in JavaScript and since we use JSX in React which itself is the extension of JavaScript, so we have to use className instead of class attribute.

How do you pass styles as props in React?

Use the React. CSSProperties type to pass CSS styles as props in React TypeScript, e.g. style: React. CSSProperties; . The CSSProperties type is used to type the style object that consists of CSS property names and values.


1 Answers

I assume you are using css loader in your webpack. You need to enable modules:true

{
  loader: 'css-loader',
  options: { 
    modules: true
  }
}

If you don't want this behaviour to be default, in your (s)css you can use:

// sCSS
:local .yourClass {...}

// JS

import cls from '../yourCss.scss'

const Component = () => (
  <div className={cls.yourClass} />
)

// yourClass will become some random hash
// or something else based on your css loader config

to have it processed. If you have modules: true and you don't want css loader to compile your class, you can use

// CSS
:global .yourGlobalClass {...}

// JS
import '../yourCss.scss'

const Component = () => (
  <div className="yourGlobalClass" />
)

See the documentation: https://github.com/webpack-contrib/css-loader and https://github.com/css-modules/css-modules

like image 192
Roman Nguyen Avatar answered Oct 13 '22 04:10

Roman Nguyen