3

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

  • Does this answer your question? [React pseudo selector inline styling](https://stackoverflow.com/questions/43701748/react-pseudo-selector-inline-styling) – Punit Makwana Nov 01 '20 at 15:12
  • @PunitMakwana Hi, I have already read this topic, I would like to manage the css with css modules, without the support of other libraries, I would like to understand if it is possible to use the pseudo classes only with css modules and inline. – Alessandro D'Aniello Nov 01 '20 at 15:21
  • you need some third party css in js library to do this. I would recommend emotionjs – Punit Makwana Nov 01 '20 at 15:24
  • in your experience do you think it is the only way to solve this problem? – Alessandro D'Aniello Nov 01 '20 at 15:58

1 Answers1

0

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>
  );
}


Tooba Ali
  • 344
  • 2
  • 5