Last active
January 24, 2018 19:25
-
-
Save ebakan/f3d94874a2e8bfbb06e3f9510c78ffd1 to your computer and use it in GitHub Desktop.
React Component for Popper.js that takes the reference as its first child and the popper as its second child (a la react-tether)
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, { Component, PropTypes } from 'react'; | |
import popperJS from 'popper.js'; | |
export default class Popper extends Component { | |
constructor(props) { | |
super(props); | |
this.state = {}; | |
this.update = this.update.bind(this); | |
} | |
update() { | |
if (this.state.popper) { | |
this.state.popper.update(); | |
this.setState({raf: window.requestAnimationFrame(this.update)}); | |
} | |
} | |
componentDidMount() { | |
let popper = new popperJS(this.refs.content, this.refs.popper, { | |
placement: 'top', | |
modifiersIgnored: ['applyStyle'], | |
arrowElement: this.refs.arrow | |
}) | |
popper.onUpdate(data => { | |
this.setState({data}); | |
}) | |
this.setState({popper}, this.update); | |
} | |
componentWillUnmount() { | |
this.state.popper.destroy(); | |
if (this.state.raf) { | |
window.cancelAnimationFrame(this.state.raf); | |
} | |
} | |
getPopperStyle(data) { | |
if (!data) { return {}; } | |
const left = Math.round(data.offsets.popper.left); | |
const top = Math.round(data.offsets.popper.top); | |
const transform = `translate3d(${left}px, ${top}px, 0)`; | |
return { | |
position: data.offsets.popper.position, | |
transform, | |
WebkitTransform: transform, | |
top: 0, | |
left: 0 | |
}; | |
} | |
render() { | |
const { children, arrow } = this.props; | |
return ( | |
<div> | |
<div ref='content' className='popper-content'> | |
{this.props.children[0]} | |
</div> | |
<div ref='popper' data-placement={this.state.data && this.state.data.placement} className='popper' style={this.getPopperStyle(this.state.data)}> | |
{this.props.children[1]} | |
{arrow && <div ref='arrow' className='arrow' />} | |
</div> | |
</div> | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example Usage: