Home > Back-end >  Css module in React component
Css module in React component

Time:11-20

Having this css module:

mymodule.module.css:

ol li:not(:last-child)::after {
  color: red;
  margin: 1px;
}

React component:

import myStyles from './mymodule.module.css';
...

export const MyComponent: React.FunctionComponent<MyComponentProps> = ({...} => {
   
   ...

   return (
            <li className={myStyles}>
             ...
            </li>
   );

There is a red line under className word which when hover states:

Type '{ readonly [key: string]: string; }' is not assignable to type 'string'.ts(2322) index.d.ts(1749, 9): The expected type comes from property 'className' which is declared here on type 'DetailedHTMLProps<LiHTMLAttributes, HTMLLIElement>'

Any suggestions?

CodePudding user response:

Your CSS file:

# Add your default tag styles
ol li:not(:last-child)::after {
  color: red;
  margin: 1px;
}

# Add your class
.my-class {
  margin: 1rem;
}

Your TSX

// import your stylesheet
import './mymodule.module.css';
...

export const MyComponent: React.FunctionComponent<MyComponentProps> =
 ({...}) => {
  ...
  // use the class as you would in HTML
  return (
   <li className="my-class">
    ...
   </li>
  );
}

CodePudding user response:

Class Name property is for assigning specific class defined in your css file if you want to apply css on li tag, you just need to import css file in ts file or if you want to give it a styling with class name, you should give its a parent a class like this:

React component:

<ol className={myStyles.abc}
  <li>
    ...
  </li>
</ol>

mymodule.module.css:

.abc li:not(:last-child)::after {
  color: red;
  margin: 1px;
}
  • Related