Last active
May 24, 2017 18:18
-
-
Save JonathonAshworth/b401810b965149348d03e2465a971201 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { PropTypes, Component } from 'react' | |
import styles from './../styles/Collapse.scss' | |
class Collapse extends Component { | |
static propTypes = { | |
open: PropTypes.bool, | |
className: PropTypes.string, | |
} | |
constructor() { | |
super() | |
this.manualUpdate = this.manualUpdate.bind(this) | |
} | |
componentDidMount() { | |
this.manualUpdate() | |
window.addEventListener('resize', this.manualUpdate) | |
} | |
componentWillUnmount() { | |
window.removeEventListener('resize', this.manualUpdate) | |
} | |
componentDidUpdate(prevProps) { | |
if(prevProps.open !== this.props.open || prevProps.children !== this.props.children) { | |
this.manualUpdate() | |
} | |
} | |
manualUpdate() { | |
const originalHeight = this.el.style.height // save height so we can revert later | |
this.el.style.height = 'auto' // manually set to auto so we can get computed height | |
const computedHeight = this.el.clientHeight | |
// manually set the height back, so now we're back to parity with pre-render state | |
this.el.style.height = originalHeight | |
// after a short delay, update the styles to their new values so css does the animation | |
setTimeout(() => { | |
if(this.props.open) { | |
this.el.style.height = computedHeight + 'px' | |
} else { | |
this.el.style.height = '0' | |
} | |
}, 10) | |
} | |
render() { | |
return ( | |
<div className={`${this.props.className} ${styles.collapse}`} ref={el => this.el = el}> | |
{this.props.children} | |
</div> | |
) | |
} | |
} | |
export default Collapse |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
.collapse { | |
transition: height 0.3s ease; | |
overflow: hidden; | |
height: 0; // avoid flash of expanded content on page load | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment