-
-
Save FezVrasta/6533adf4358a6927b48f7478706a5f23 to your computer and use it in GitHub Desktop.
React Component for Popper.js v1 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 { | |
state = {} | |
update = () => { | |
if (this.popperInstance) { | |
this.popperInstance.scheduleUpdate(); | |
} | |
} | |
componentDidMount() { | |
this.popperInstance = new PopperJS(this.content, this.popper, { | |
placement: 'top', | |
modifiers: { | |
arrow: { element: this.arrow }, | |
applyStyle: { enabled: false }, | |
}, | |
onCreate: (data) => this.setState({data}), | |
onUpdate: (data) => this.setState({data}) | |
}); | |
} | |
componentWillUnmount() { | |
this.popperInstance.destroy(); | |
} | |
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 | |
}; | |
} | |
getArrowStyle(data) { | |
if !(data) { return {}; } | |
const left = Math.round(data.offsets.arrow.left); | |
const top = Math.round(data.offsets.arrow.top); | |
return { position: 'absolute', top, left }; | |
} | |
render() { | |
const { children, arrow } = this.props; | |
return ( | |
<div> | |
<div | |
ref={(el) => (this.content = el)} | |
className='popper-content' | |
> | |
{this.props.children[0]} | |
</div> | |
<div | |
ref={(el) => (this.popper = el)} | |
data-placement={this.state.data && this.state.data.placement} | |
className='popper' | |
style={this.getPopperStyle(this.state.data)} | |
> | |
{this.props.children[1]} | |
{arrow && <div | |
ref={(el) => (this.arrow = el)} | |
className='arrow' | |
style={this.getArrowStyle(this.state.data)} | |
/>} | |
</div> | |
</div> | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment