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>                
3
  • 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: stackoverflow.com/questions/3508605/… Mar 20, 2018 at 16:45
  • does styled-components support sass like syntax &.open { ? Mar 20, 2018 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? Mar 20, 2018 at 17:24

1 Answer 1

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

2
  • 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. Mar 21, 2018 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 developer.mozilla.org/en-US/docs/Web/CSS/…. Mar 21, 2018 at 15:18

Your Answer

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

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