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.
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.
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.
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.
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
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