Skip to content

Instantly share code, notes, and snippets.

@ebakan
Last active January 24, 2018 19:25
Show Gist options
  • Save ebakan/f3d94874a2e8bfbb06e3f9510c78ffd1 to your computer and use it in GitHub Desktop.
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)
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>
);
}
}
@ebakan
Copy link
Author

ebakan commented Apr 11, 2016

Example Usage:

render() {
  const { user, target } = this.props;
  return (
    <Popper arrow>
      <div className='preview user'>
        <div className='icon'>
          <Avatar user={user} defaultIcon={require('../assets/account-icon-white.png')}/>
        </div>
        <div className='name'>{user.name}</div>
      </div>
      <div className='drag-hint'>
        {this.renderHintText(user, target)}
      </div>
    </Popper>
  );
}

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