I want use 2 classes on 1 components React. its both has own module css self. i check there no typo on filename and props but css doesn't attach.
import React from "react";
import styles from "./Card.module.css";
const Card = (props) => {
return (
<div className={{...styles.Card, ...props.className}}>
{props.children}
</div>
);
};
export default Card;
anyone know why?
The prop className
needs to be a string. In order to have 2 classes you need to concat them.
Documentation: https://reactjs.org/docs/faq-styling.html
<div className={`${styles.Card} ${props.className}`}>
{props.children}
</div>
If you want to improve this, you can use the package classnames
, which is widely used to conditionally set class names to components.
https://www.npmjs.com/package/classnames
The classNames function takes any number of arguments which can be a string or object. The argument 'foo' is short for { foo: true }. If the value associated with a given key is falsy, that key won't be included in the output.
classNames('foo', 'bar'); // => 'foo bar'
classNames('foo', { bar: true }); // => 'foo bar'
classNames({ 'foo-bar': true }); // => 'foo-bar'
classNames({ 'foo-bar': false }); // => ''
classNames({ foo: true }, { bar: true }); // => 'foo bar'
classNames({ foo: true, bar: true }); // => 'foo bar'
// lots of arguments of various types
classNames('foo', { bar: true, duck: false }, 'baz', { quux: true }); // => 'foo bar baz quux'
// other falsy values are just ignored
classNames(null, false, 'bar', undefined, 0, 1, { baz: null }, ''); // => 'bar 1'