How do you use Pseudo-classes in React using css modules?

Viewed 760

The example I worked on is the following:

I have a button component that receives the background color as props. The received color will be the background that the button must have when hovering.

Second question: The only way to use props in css, using css modules, is to apply the inline style in the js file where you declare the component?

Below I insert a code base (in the example the background color is applied by default):

import Button from "./Button";

export default function App() {
  return <Button hoverColor={"red"} />;
}

...

export default function Button({ hoverColor }) {
  const buttonStyle = {
    backgroundColor: hoverColor
  };
  return <button style={buttonStyle}>click me!</button>;
}

Thanks

1 Answers

You may use React useState Hook to achieve the desired functionality: (Your Button component should look like this)

import React, { useState } from "react";

export default function Button({ hoverColor }) {
  const [color, setColor] = useState("");

  const buttonStyle = {
    backgroundColor: color
  };
  return (
    <button
      style={buttonStyle}
      onMouseOver={() => setColor(hoverColor)} //set the color when user hovers over the button
      onMouseOut={() => setColor("")} //set color to an empty string otherwise
    >
      click me!
    </button>
  );
}


Related