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

how can I add a module style, via props other components

codesandbox

I have a component

const UIComponent = ({ className }: Props) => {
  return (
    <div
      className={classNames(styles.component, styles.green, {
        className: className <--how to make it work?
      })}
    >
      Component
    </div>
  );
};

^ here the className class is simply added, if the className prop is passed, I need to somehow pass the styles through this prop

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

styles for UIComponent

.component {
  font-size: 24px;
}
.green {
  color: green;
}

const App = () => {
  return (
    <>
      <UIComponent className={styles.red} />
      {/* ^^^ it should be red*/} 
      <UIComponent />
    </>
  );
};

styles for App

.App {
  font-family: sans-serif;
  text-align: center;
}

.red{
  color: red;
}

how I can add className in another component

>Solution :

The className should be passed through directly, rather than in an object:

const UIComponent = ({ className }: Props) => {
  return (
    <div
      className={classNames(styles.component, styles.green, className)}
    >
      Component
    </div>
  );
};

This still doesn’t turn the component red, as there are two color style rules with the same specificity, so the one which is loaded last (in this case, the green) takes precedence. The ugly workaround for this would be:

.red {
  color: red !important;
}

It’s best practice to avoid using !important so you’ll probably want to find a better solution to making that more specific, such as nested classes.

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