Skip to content

Instantly share code, notes, and snippets.

@ixahmedxi
Last active February 23, 2018 18:24
Show Gist options
  • Save ixahmedxi/ac03a036d6890c5ea8c52cc0b3dab469 to your computer and use it in GitHub Desktop.
Save ixahmedxi/ac03a036d6890c5ea8c52cc0b3dab469 to your computer and use it in GitHub Desktop.
React component that changes className when in view
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import Waypoint from 'react-waypoint'
class ClassPoint extends Component {
constructor(props) {
super(props)
this.state = { active: false }
this.onEnter = this.onEnter.bind(this)
this.onLeave = this.onLeave.bind(this)
}
onEnter() {
this.setState({ active: true })
}
onLeave() {
this.setState({ active: false })
}
render() {
return (
<Waypoint
onEnter={this.onEnter}
onLeave={this.onLeave}
horizontal={this.props.horizontal}
topOffset={this.props.topOffset}
bottomOffset={this.props.bottomOffset}
>
<div className={this.state.active ? this.props.activeClass: ''}>
{this.props.children}
</div>
</Waypoint>
)
}
}
ClassPoint.propTypes = {
activeClass: PropTypes.string,
horizontal: PropTypes.bool,
topOffset: PropTypes.oneOfType([
PropTypes.number,
PropTypes.string
]),
bottomOffset: PropTypes.oneOfType([
PropTypes.number,
PropTypes.string
])
}
ClassPoint.defaultProps = {
activeClass: 'active'
}
export default ClassPoint
@ixahmedxi
Copy link
Author

ixahmedxi commented Feb 23, 2018

This React component relies on the package 'react-waypoint' to determine if the child of the component is in view or not and if it is, it will use the activeClass prop to inject new classNames into the child. When the child is out of view, it will go back to having no classes at all. The component also provides common react-waypoint options like horizontal, topOffset and bottomOffset. Hope you all enjoy this cause I mainly use react-waypoint to change the styles and add animations when it goes in view and this makes it simpler to do so and it makes your code more dry <3. This will also just add the class of 'active' on view if no activeClass prop was provided.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment