Working on a React project using Webpack. Adding some styles in style.css and importing into component with import style from './style.css';
. Elements without selectors added like body
, div
, get styled fine, but I am running into issues with classes.
Setting className with <div className='foo'>foo div</div>
.
css:
.foo {
height: 250px;
width: 250px;
background-color: blue !important;
}
body {
background-color: red;
}
The red background color gets applied to the body, but .foo
div gets nothing...when I check out foo
div in DevTools it has its class name (<div class="foo">foo div</div>
) and the stylesheet is intact:
.foo {
height: 250px;
width: 250px;
background-color: blue !important;
}
body {
background-color: red;
}
I have been trying to figure this out for awhile and have tried a lot of things...basically all DOM elements can be styled, but as soon as I try to add any kind of selector I get nothing...
Your webpack configuration may be changing the class name depending on its settings. (CSS Modules enabled, though your comment about stylesheet intact implies it's not).
Since you are importing the './style.css' file, try referencing the class name like: style.foo. Ex:
<div className={ style.foo }>foo div</div>
This article: http://javascriptplayground.com/blog/2016/07/css-modules-webpack-react/ describes the pattern of importing and referencing the class name pretty well.
If you're like me and use the style attribute for styling then afterwards move them into proper classes in .css files (and wonder why it doesn't work), remember to remove the JSX string format,
height: "100px"
is not the same as
height: 100px
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