Home > front end >  CSS selector attributes does not work when adding style to component
CSS selector attributes does not work when adding style to component

Time:03-16

I am having this React component:

import * as React from "react";
import styles from "./style.module.css";

export interface IMenuButtonProps {
  name: string;
  onClick?: () => void;
  btnColor?: string;
}

const MenuButton: React.FunctionComponent<IMenuButtonProps> =
  function menuButton({
    name = "Unamed Button",
    onClick,
    btnColor,
  }: IMenuButtonProps) {
    return (
      <button
        className={styles.btn}
        type="button"
        onClick={onClick}
        style={{ color: btnColor }}
      >
        {name}
      </button>
    );
  };
export default MenuButton;

and this CSS file:

.btn {
  border: none;
  height: 100px;
}
.btn:hover {
  color: chartreuse;
}

The hover selector attribute does not work when adding:

 style={{ color: btnColor }}

Border and height works fine. I suspect it changes color for both btn and btn:hover. Anyone knows what happens or how to change only btn and not btn:hover?

CodePudding user response:

The problem is that when you add color like this

style={{ color: btnColor }}

you are adding styles inline to your HTML, so it is more important than css classes. This is a common problem when mixing CSS classes with inline CSS.

To solve problem convert inside component 'btnColor' prop to some css class and then you can combine classes for example with library called 'classnames'. Also I like to specify in props interface what colors are availble in component. For example I would write it like this:

export interface IMenuButtonProps {
  name: string;
  onClick?: () => void;
  btnColor?: 'red' | 'blue' | 'black';
}

CodePudding user response:

You can pass css variables into your inline style declaration like so

<button
  className={styles.btn}
  type="button"
  onClick={onClick}
  style={{ "--hover-color: `${btnColor}`;" }}
>
  {name}
</button>

And then in your stylesheet, simply reference the variable as such

.btn:hover {
  color: var(----hover-color);
}
  • Related