Pass a value from react component to scss
P粉463824410
P粉463824410 2023-09-13 13:35:11
0
1
551

I have the following code in a .jsx component,

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

In .scss, how to use the list mode of headerContainer class? For example:

.headerContainer.listmode{

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

            margin: 20px 0px 100px 0px;
            }

P粉463824410
P粉463824410

reply all(1)
P粉274161593

You can reverse the relationship with css-modules, I recommend setting it up in a build system like Webpack (e.g. using sass-loader and css- loader plugin). The class name can then be imported into JavaScript. By default, each class is locally scoped (i.e. given a unique name), but this can be changed using 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}>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template