@bigfishtv/cockpit
Version:
61 lines (51 loc) • 1.64 kB
JavaScript
import PropTypes from 'prop-types'
import React, { Component } from 'react'
import * as scrollUtils from '../../utils/scrollUtils'
/**
* Wrapper for a section that determines whether or not it should update based on if it's visible
* This makes rendering less expensive on huge complex pages with many sections
*/
export default class Section extends Component {
static propTypes = {
/** Section component */
Component: PropTypes.func.isRequired,
/** Component icon */
icon: PropTypes.string,
/** Section property, e.g. hero_sections */
sectionProperty: PropTypes.string,
collapsed: PropTypes.bool,
isNew: PropTypes.bool,
onToggleCollapsed: PropTypes.func,
onDuplicate: PropTypes.func,
onRemove: PropTypes.func,
onReorder: PropTypes.func,
}
el = null
state = { inView: true }
componentDidMount() {
scrollUtils.addListener(this.handleScroll)
}
componentWillUnmount() {
scrollUtils.removeListener(this.handleScroll)
}
handleScroll = (scroll, windowHeight) => {
const position = this.el.getBoundingClientRect()
const inView = position.bottom > 0 && position.top < windowHeight
if (inView !== this.state.inView) {
this.setState({ inView })
}
}
shouldComponentUpdate(nextProps, nextState) {
// if (!this.state.inView && nextState.inView) console.log(this.props.sectionProperty + ' now in view')
// if (this.state.inView && !nextState.inView) console.log(this.props.sectionProperty + ' out of view')
return nextState.inView
}
render() {
const { Component, ...props } = this.props
return (
<div ref={el => (this.el = el)}>
<Component {...props} />
</div>
)
}
}