Search code examples
reactjscss-modulesreact-css-modules

CSS Modules Value is not retrieved


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

Solution

  • - 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.