Skip to content

Instantly share code, notes, and snippets.

@JonathonAshworth
Last active May 24, 2017 18:18
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JonathonAshworth/b401810b965149348d03e2465a971201 to your computer and use it in GitHub Desktop.
Save JonathonAshworth/b401810b965149348d03e2465a971201 to your computer and use it in GitHub Desktop.
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
.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