Home > Enterprise >  Using css module in react app. How can I get rid of styles keyword
Using css module in react app. How can I get rid of styles keyword

Time:02-12

I used css modules in my react app and here is my code:

import styles from './PlayerCard.module.css';
import PlayerPhoto from '../../images/players/Farahani.png';

export default function PlayerCard() {
  return (
    <div className={styles.PlayerCard}>
      <img className={styles.PlayerPhoto} src={PlayerPhoto} alt="Player" />
      <p className={styles.PlayerName}>Farahani</p>

      <div className={styles.SkillBox}>
        <div className={styles.SkillName}>
          <p>Defence:</p>

How can I get rid of those styles keywords? is there any way like destructuring or something?

CodePudding user response:

Yes you can use Object destructuring.

import styles from './PlayerCard.module.css';
import PlayerPhoto from '../../images/players/Farahani.png';

const { PlayerCard: PlayerCardStyle, PlayerPhoto: PlayerPhotoStyle, PlayerName: PlayerNameStyle, SkillBox, SkillName } = styles;

export default function PlayerCard() {
  return (
    <div className={PlayerCardStyle}>
      <img className={PlayerPhotoStyle} src={PlayerPhoto} alt="Player" />
      <p className={PlayerNameStyle}>Farahani</p>

      <div className={styles.SkillBox}>
        <div className={styles.SkillName}>
          <p>Defence:</p>

Note that for PlayerCard, PlayerPhoto, and PlayerName, I need to alias it to different names so that they don't get conflicted with the components' names.

Alternatively, you can also import the styles like below:

import { PlayerCard as PlayerCardStyle, PlayerPhoto as PlayerPhotoStyle, PlayerName as PlayerNameStyle, SkillBox, SkillName } from './PlayerCard.module.css'

Similarly, you also have to alias the imports.

  • Related