1

I have the following code in .jsx component,

<div className={type === "travellist" ? "headerContainer listmode" : "headerContainer"}>

In .scss how do I use the listmode for the class headerContainer? For example:

.headerContainer.listmode{

            margin: 20px 0px 40px 0px;
            }
or 
    .headerContainer{

            margin: 20px 0px 100px 0px;
            }
user1306926
  • 135
  • 1
  • 1
  • 5

2 Answers2

0

You can invert the relationship with css-modules, which I recommend setting up in a build system like Webpack (e.g. with the sass-loader & css-loader plugins). The class names can then be imported into your JavaScript. By default, each class is locally scoped (i.e. given unique names) but that can be changed with the available options.

/* In your stylesheet */
.headerContainer.listmode {
    margin: 20px 0px 40px 0px;
}
.headerContainer{
    margin: 20px 0px 100px 0px;
}
// In JS
import { headerContainer, listmode } from './style.scss';

const className = type === 'travellist' ? `${headerContainer} ${listmode}` : `${headerContainer}`;
<div className={className}>
Chrisp
  • 26
  • 1
  • 4
  • Good suggestion, but How do I export .headerContainer.listmode and .headerContainer in .scss? – user1306926 Jul 20 '23 at 06:31
  • Exporting of the defined class names is handled by the css-modules plugin. Here's [an example](https://github.com/css-modules/webpack-demo) of setting up the loader for Webpack. – Chrisp Jul 20 '23 at 18:00
0

I think this article will help you. Can i send parameters from React to SCSS?

But I'm not sure why we need to send variables from React components to scss. I would appreciate it if you could let me know.

Diego Ammann
  • 463
  • 7