Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading