Skip to content

Instantly share code, notes, and snippets.

@charud
Last active December 30, 2016 19:39
Show Gist options
  • Save charud/3d5062f911da467b525d6040200334bd to your computer and use it in GitHub Desktop.
Save charud/3d5062f911da467b525d6040200334bd to your computer and use it in GitHub Desktop.
import React from 'react';
import listener from 'react-contextmenu/modules/globalEventListener';
export default function connectMenu(id) {
return function connectMenuWrapper(Child) {
return class ConnectMenu extends React.Component {
constructor(props) {
super(props);
this.state = { item: null };
this.handleShow = this.handleShow.bind(this);
this.handleHide = this.handleHide.bind(this);
}
componentDidMount() {
this.listenId = listener.register(this.handleShow, this.handleHide);
}
componentWillUnmount() {
if (this.listenId) {
listener.unregister(this.listenId);
}
}
handleShow(e) {
if (e.detail.id !== id) return;
// Don't include attributes, children or the collect function in the state.
const filteredData = {};
for (const key in e.detail.data) {
if (['attributes', 'children', 'collect'].indexOf(key) === -1) {
filteredData[key] = e.detail.data[key];
}
}
this.setState({item: filteredData});
}
handleHide() {
this.setState({item: null});
}
render() {
return <Child {...this.props} {...this.state} />;
}
};
};
}
import React from 'react';;
import { ContextMenu, MenuItem } from 'react-contextmenu';
import { MENU_ID } from './constants';
const Menu = (props) => {
return (
<ContextMenu id={MENU_ID}>
<MenuItem>Play {props.item.name}</MenuItem>
{props.item.isInCollection ?
<MenuItem>Remove</MenuItem> :
<MenuItem>Add</MenuItem>}
</ContextMenu>
)
}
export default connectMenu(MENU_ID)(Menu);
import React from 'react';
import { MENU_ID } from './constants';;
import { ContextMenuTrigger } from 'react-contextmenu'
const SomeComponent = (props) => {
return (
<div>
<ContextMenuTrigger id={MENU_ID} collect={props => props} name="Foo">
<div>...</div>
</ContextMenuTrigger>
<ContextMenuTrigger id={MENU_ID} collect={props => props} name="Bar" isInCollection>
<div>...</div>
</ContextMenuTrigger>
</div>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment