'how can I add a module style, via props other components
I have a component
const UIComponent = ({ className }: Props) => {
return (
<div
className={classNames(styles.component, styles.green, {
className: className <--how to make it work?
})}
>
Component
</div>
);
};
^ here the className class is simply added, if the className prop is passed, I need to somehow pass the styles through this prop
styles for UIComponent
.component {
font-size: 24px;
}
.green {
color: green;
}
const App = () => {
return (
<>
<UIComponent className={styles.red} />
{/* ^^^ it should be red*/}
<UIComponent />
</>
);
};
styles for App
.App {
font-family: sans-serif;
text-align: center;
}
.red{
color: red;
}
how I can add className in another component
Solution 1:[1]
The className should be passed through directly, rather than in an object:
const UIComponent = ({ className }: Props) => {
return (
<div
className={classNames(styles.component, styles.green, className)}
>
Component
</div>
);
};
This still doesn't turn the component red, as there are two color style rules with the same specificity, so the one which is loaded last (in this case, the green) takes precedence. The ugly workaround for this would be:
.red {
color: red !important;
}
It's best practice to avoid using !important so you'll probably want to find a better solution to making that more specific, such as nested classes.
Solution 2:[2]
You could use the className property if it exists, otherwise use the style.green class :
const UIComponent = ({ className }: Props) => {
console.log(className);
return (
<div
className={classNames(
styles.component,
className || styles.green,
)}
>
Component
</div>
);
};
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Zorac |
| Solution 2 | Fraction |
