I am trying to create a component with dynamic classNames to apply different styles based on the name. So far I can get the different names to show up when I check with the inspection tool but the styling stays doesn't change.
The button component:
import { ListButtonProps } from "./ListButtonProps";
import styles from "./ListButton.module.scss";
const ListButton: FC<ListButtonProps> = ({
buttonType,
backgroundColor,
color,
borderWidth,
fontSize,
fontWeight,
width,
height,
gap,
children,
onClick,
}) => {
return (
<div
className={[styles.listButton, buttonType].join(" ")}
style={{
backgroundColor: backgroundColor,
color: color,
borderWidth: borderWidth,
fontSize: fontSize,
fontWeight: fontWeight,
width: width,
height: height,
gap: gap,
}}
>
<>{children}</>
</div>
);
};
export { ListButton };
The styleSheet:
.listButton .title {
display: flex;
justify-content: center;
}
In the inspection tool the className is "ListButton-module-listButton_KIOLE title", and it shows the inline style but not the CSS styling.
Any help will be appreciated.
CodePudding user response:
CSS modules munges the class names, so it's not going to be .title
in the stylesheet output. You'd need to reference the type via styles
too.
And I might be missing something (highly likely) but it's not clear to me why you're hyphenating and joining the class names.
className={`${styles.listButton} ${styles[buttonType]}`}
Should output the module equivalent of .
CodePudding user response:
I ended up using a switch statement to handle the differing classNames
import React, { FC } from "react";
import { ListButtonProps } from "./ListButtonProps";
import styles from "./ListButton.module.scss";
const ListButton: FC<ListButtonProps> = ({
buttonType,
backgroundColor,
color,
borderWidth,
fontSize,
fontWeight,
width,
height,
gap,
children,
onClick,
}) => {
/**
* Uses the buttonType prop to return a div with a unique
* className to ensure scss styling adopted per div.
* @param {string}
* @returns {JSX.Element}
*/
function returnStyledButton(buttonType: string) {
switch (buttonType) {
case "title":
return (
<div
className={styles.title}
style={{
backgroundColor: backgroundColor,
color: color,
borderWidth: borderWidth,
fontSize: fontSize,
fontWeight: fontWeight,
width: width,
height: height,
gap: gap,
}}
>
<>{children}</>
</div>
);
case "avatarTitle":
return (
<div
className={styles.avatarTitle}
style={{
backgroundColor: backgroundColor,
color: color,
borderWidth: borderWidth,
fontSize: fontSize,
fontWeight: fontWeight,
width: width,
height: height,
gap: gap,
}}
>
<>{children}</>
</div>
);
case "avatarTitleInfo":
return (
<div
className={styles.avatarTitleInfo}
style={{
backgroundColor: backgroundColor,
color: color,
borderWidth: borderWidth,
fontSize: fontSize,
fontWeight: fontWeight,
width: width,
height: height,
gap: gap,
}}
>
<>{children}</>
</div>
);
}
}
return <>{returnStyledButton(buttonType)}</>;
};