7

I want to apply a &:hover only when a prop is passed - in this situacion: animated

const AnimationContainer = styled.div`
  transform: translate(0%);
  transition: 0.3s ease-out;

  &:hover { // apply hover only when $(props.animated) is paased
     position: fixed;
     transform: translate(0%, -30%);
     transition: 0.3s ease-out;
   }
`;

Does anyone have a suggestion how to do it? I guess it would be possible to apply the styling for every property just starting with .. :$(props => props.animated ? ..), but is there a simpler solution?

1 Answer 1

25

Yup! Like this:

import styled, { css } from 'styled-components'

const AnimationContainer = styled.div`
  transform: translate(0%);
  transition: 0.3s ease-out;

  ${props => props.animated && css`
    &:hover {
      position: fixed;
      transform: translate(0%, -30%);
      transition: 0.3s ease-out;
    }
  `}
`

export default AnimationContainer

And then you may use it like this:

import AnimationContainer from './path/to/AnimationContainer

// some component here…
  render() {
    return (
      <!-- some JSX element… -->
        <AnimationContainer animated>
          With animation
        </AnimationContainer>
        <AnimationContainer>
          Without animation
        </AnimationContainer>
      <!-- end of some JSX element… -->
    )
  }

Learn more about props and css in Styled Components.

2
  • I'm confused. I see how that works if animated prop is passed, but what about the :hover pseudo-class? To me, the above won't do anything when hovering over the div.
    – skube
    Commented Mar 13, 2018 at 13:46
  • 1
    @skube You're right, I forgot about that, edited to fix. The css is just inserted in the outer one, so you can just add the &:hover selector as you normally would.
    – Raicuparta
    Commented Mar 19, 2018 at 19:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.