Tom Tom - 3 months ago 93
React JSX Question

Right Click Menu using React JS

I'd like to know if there is a best practice/correct way to setup a right-click menu for a React component.

I currently have this...

// nw is nw.gui from Node-Webkit
componentWillMount: function() {
var menu = new nw.Menu();
menu .append(new nw.MenuItem({
label: 'doSomething',
click: function() {
// doSomething
}
}));

// I'd like to know if this bit can be done in a cleaner/more succinct way...
// BEGIN
var that = this;
addEventListener('contextmenu', function(e){
e.preventDefault();
// Use the attributes property to uniquely identify this react component
// (so different elements can have different right click menus)
if (e.target.attributes[0].nodeValue == that.getDOMNode().attributes[0].nodeValue) {
menu.popup(e.x, e.y);
}
})
// END
},


This works, but it feels a little messy and I was wondering if there was another approach I might be able to use, any information would be greatly appreciated,

Thanks!

Tom Tom
Answer

UPDATE:

Figured it out - here is what you can do

var addMenu;

componentWillMount: function() {
    addMenu = new nw.Menu();
    addMenu.append(new nw.MenuItem({
        label: 'doSomething',
        click: function() {
            // doSomething
        }
    }));
},

contextMenu: function(e) {
    e.preventDefault();
    addMenu.popup(e.clientX, e.clientY);
},

render: function(){
    return <button onClick={this.handleClick} onContextMenu={this.contextMenu}>SomethingUseful</button>
}

In render you can pass a function to onContextMenu for when a right click occurs for this react component.