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

Advertisements

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

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.

Leave a ReplyCancel reply