Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Styled Components: props for hover

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?

like image 278
Tomas Eglinskas Avatar asked Dec 04 '17 14:12

Tomas Eglinskas


People also ask

Can you use props in styled-components?

Props can be passed to styled components just as they are with regular React components (class or functional). This is possible because styled components are actually React components. styled-components creates a React component, which renders an HTML tag corresponding to the property in the styled object.

How do you access props in styled-components?

To pass props to React components created with styled-components, we can interpolate functions into the string that creates the component. We create the ArrowStyled component with the styled. div tag. Then string that we pass into the tag has the rotate value set from a prop.

What is shouldForwardProp?

shouldForwardProp ( (prop: string) => bool [optional]): Indicates whether the prop should be forwarded to the Component .


1 Answers

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.

like image 82
Raicuparta Avatar answered Sep 28 '22 02:09

Raicuparta