skip to Main Content

Im started learn react, but can’t understand, why my style doesn’t work in @hover?

Button – is a custom library button. By default I can change its color in "style" line, but I can’t change it on hover effect.

const linkStyle = {
background: 'red',
'&: hover': {background: 'blue'}
}

export default function App() {
return (
<Theme className="App">
‹Button
label="My Button"
iconLeft={IconAlert}
size="m"
style={linkStyle}
</Theme>

Where am I wrong?

I tried many many many times

2

Answers


  1. hover can’t be applied at inline-css, you can use the sx prop to provide the CSS –

      const linkStyle = {
        background: "red",
        "&:hover": {
          background: "blue",
        },
      };
    
      <MuiButton sx={linkStyle}>Button</MuiButton>
    
    Login or Signup to reply.
  2. By React best practices, it’s better to split your component into 2 different files, ie; component file and styling file. Finally import the style into the component file to enable the CSS styles declared. Example based your code above as below:

    CSS file

    // lets say the name of the file is -> Component.css
    .linkStyle {
      background: 'red';
      &:hover {
        background: 'blue';
      }
    }
    
    

    React Component File

    // Let say your component file name is -> Component.js, importing the styles here as below;
    import Styles from './Component.css';
    
    export default function App() {
    return (
      <Theme className="App">
       <Button 
         form="default" 
         view="primary" 
         label="My Button"
         iconLeft={IconAlert}
         size="m"
         className={Styles.linkStyle}
       />
      </Theme>
    )}
    
    

    This should work if your component file and styles file are in the same directory or folder. Hope this helps

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search