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>
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