Skip to content

Instantly share code, notes, and snippets.

@JingleChannel
Forked from FezVrasta/Popper.jsx
Last active February 9, 2017 18:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JingleChannel/b32e29dbc9cac4dee0641667aef0aa9f to your computer and use it in GitHub Desktop.
Save JingleChannel/b32e29dbc9cac4dee0641667aef0aa9f 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)
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