React sharing behavior of external CSS file - body background for components

133 views Asked by At

how can I change React sharing behavior of an external CSS file in React, so I can set the body background different for different components?

login.css

body {
  background-image: url('../../../images/bannerbackground.png');
}

home.css

body {
  background-color: rgb(185, 174, 160);
}

but for react's sharing behavior with the components of the same root I cannot differentiate it, is there any solution?

1

There are 1 answers

2
Harry On

Yes there is a solution. Its pretty simple. To prevent the clashes you can implement CSS modules. Rename your CSS files to filename.module.css

Result:

// note the classname generated 
<button class="Button_error_ax7yz">Error Button</button>

According to the official repo CSS Modules are “CSS files in which all class names and animation names are scoped locally by default”. What does this mean? CSS Modules are not specs or an implementation in the browser, but rather a process in a build step (with the help of Webpack or Browserify) that changes class names and selectors to be scoped (kinda like namespaced)