Skip to content

Instantly share code, notes, and snippets.

@chrisgalvan
Forked from ebakan/Popper.js
Created October 11, 2017 15:46
Show Gist options
  • Save chrisgalvan/9a1e7757f0cb7179a96cb0d7f5fb3baf to your computer and use it in GitHub Desktop.
Save chrisgalvan/9a1e7757f0cb7179a96cb0d7f5fb3baf 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)
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