Home > Software design >  How to change other element when hover by using 'styled'
How to change other element when hover by using 'styled'

Time:12-20

I'm new to Mui and trying to apply animation to components.

What I want to do is, I have four same component and each has its own image.

 <MyComponent>some images...</MyComponent>
 <MyComponent>some images...</MyComponent>
 <MyComponent>some images...</MyComponent>
 <MyComponent>some images...</MyComponent>

const MyComponent = styled("div")((theme) => ({

  //... some styles. 

  // scale up when hovered
  '&:hover': {
      transform: "scale(1.2)",
      marginRight: "20px",
   
  }
}));

If I hover a <MyComponent>, I want to scale up hovered one, and scale down others.

Is there any ways to defined such action by using styled???

CodePudding user response:

I would set a state then use a conditional to change styles .. IE

const [hoverState, setHoverState] = useState(false);


<MyComponent
   onm ouseOver={setHoverState(true)}
   onm ouseOut={setHoverState(false)}
   style={hoverState ? {transform: "scale(1.2)",marginRight: "20px",} : ''}
   >
       some images...
</MyComponent>

CodePudding user response:

You can do this with css and styled-components.

Note that the styled function is not meant to be called directly, but passed a template literal. Inside the template literal, you can write regular css expressions.

codesandbox

const MyComponent = styled.div`
  transform: scale(1);
  margin-right: 0px;

  :hover {
    transform: scale(1.2);
    margin-right: 20px;
  }
`;
  • Related