6

I am trying to create a simple collapsable div using styled-components in react.

I can get the div to toggle open and close based on state but I cannot seem to get the transition to work. It just jumps to open or closed.

Styled Component:

const Details = styled.div`
    transition: 0.3s ease-out;

    &.open {
        height: auto;
        padding: 25px 0;
    }

    &.closed {
        height: 0;
        overflow: hidden;
    }
`;

JSX

<Details className={this.state.detailsOpen ? 'open' : 'closed'}>
    {stuff}
</Details>                
user8467470
  • 780
  • 3
  • 10
  • 25
  • 1
    You can't transition `height` to `auto` (you're also missing `height` in the `transition` rule declaration). You can, however, transition `max-height`, which is the usual workaround for this purpose, see: https://stackoverflow.com/questions/3508605/how-can-i-transition-height-0-to-height-auto-using-css – Miguel Calderón Mar 20 '18 at 16:45
  • does styled-components support sass like syntax `&.open {` ? – Tomasz Mularczyk Mar 20 '18 at 16:46
  • Thanks Miguel, I tried a number of approaches using that advice and the behaviour remains the same. Is it because I am conditionally changing the class 'open' and removing it all together from the styled element? – user8467470 Mar 20 '18 at 17:24

1 Answers1

12

As stated in the comments, you'll need to use max-height if you want to trigger the animation. Since you're using styled-components, it's probably better to not rely on className and just pass the state as a prop to the component directly:

JSX

<Details open={this.state.detailsOpen}>
    {stuff}
</Details> 

Styled Component

const Details = styled.div`
    max-height: ${props => props.open ? "100%" : "0"};
    overflow: hidden;
    padding: ${props => props.open ? "25px 0" : "0"};
    transition: all 0.3s ease-out;
`;

I threw an example together on code sandbox: https://codesandbox.io/s/1qrw632214

Matt Waldron
  • 1,738
  • 1
  • 14
  • 11
  • 1
    Thanks Matt. I had a play with the demo and works great. I still can't seem to get the transition to work. Just jumps still but at least I know this works so will track down what is stopping it elsewhere. – user8467470 Mar 21 '18 at 14:43
  • 1
    No problem, good luck! You may want to check any immediate parent elements that may also exhibit any display/hide behavior with properties that cannot be animated https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_animated_properties. – Matt Waldron Mar 21 '18 at 15:18