Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS class selector styles not being applied in React Project

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

like image 288
robbieyng Avatar asked Jun 27 '17 21:06

robbieyng


2 Answers

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.

like image 197
Kyle Swanson Avatar answered Oct 21 '22 23:10

Kyle Swanson


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
like image 29
James Salamon Avatar answered Oct 21 '22 23:10

James Salamon