Reputation: 734
I'm using CSS Modules in my react application. Depending on the props value, if it is blue or white, i want to use the respected class from the "styles" import. However, when i run the code and inspect the p element, i see that class name is shown as "styles.blue-text" for example, but the value of it is not retrieved from the respecting css file. Why it is not applied, although the class name is correctly fetched.
import React,{useEffect, useState} from "react"
import DarkBlueRightArrow from "../../../resources/images/shared/darkblue-right-arrow.svg"
import styles from "./LeftSidedCircularDarkBlueArrowButton.module.css"
const LeftSidedCircularDarkBlueArrowButton = props => {
const [color,setColor] = useState("")
useEffect(() => {
if(props.color === "white")
setColor("styles.white-text")
if (props.color === "blue")
setColor("styles.blue-text")
});
return (
<a href={props.detailLink}>
<div className="d-flex align-items-center justify-content-ceter">
<img className={styles.icon} src={DarkBlueRightArrow} alt="" />
<p className={color}>{props.text}</p>
</div>
</a>
)
}
export default LeftSidedCircularDarkBlueArrowButton
Upvotes: 0
Views: 500
Reputation: 25
If you prefer with the -
way when dealing with CSS modules, simply adding .toString()
definitely works.
const LeftSidedCircularDarkBlueArrowButton = props => {
// ...
const color = props.color === "white"
? styles['white-text'].toString()
: styles['blue-text'].toString()
return (
<a href={props.detailLink}>
<div className="d-flex align-items-center justify-content-ceter">
<img className={styles.icon} src={DarkBlueRightArrow} alt="" />
<p className={color}>{props.text}</p>
</div>
</a>
)
}
Without .toString()
, it doesn't return a class and only returns the initial state you set it in and vice versa.
Upvotes: 0
Reputation: 3685
-
is not valid when used with dot object notation. You have to use the bracket notation instead.
Also state is not required when it can be calculated with props.
...
const LeftSidedCircularDarkBlueArrowButton = props => {
/* const [color,setColor] = useState("") */
/* useEffect(() => {
if(props.color === "white")
setColor("styles.white-text")
if (props.color === "blue")
setColor("styles.blue-text")
}); */
const color = props.color === "white" ? styles['white-text'] : styles['blue-text']
return (
<a href={props.detailLink}>
<div className="d-flex align-items-center justify-content-ceter">
<img className={styles.icon} src={DarkBlueRightArrow} alt="" />
<p className={color}>{props.text}</p>
</div>
</a>
)
}
...
That's why CSSModules prefer naming class names in camelCase, so to avoid the bracket notation.
Upvotes: 1