orpqK
orpqK

Reputation: 2795

Display a div at the position of mouse click

I have a table of cells, and I want to be able to create a menu on the point of right click. I have an example of my fiddle here: jsFiddle

Now the ContextMenu class is just a div that I created for this example. As you can see there are no borders to form the actual menu. Now how can I make this menu display at the position my mouse is when I click on one of these cells? Right now it displays under the current table div.

Do I need to mount the menu div under componentWillMount() ?

Upvotes: 0

Views: 5705

Answers (1)

Dhiraj
Dhiraj

Reputation: 33628

onContextMenu method gives the location of mouse click as e.pageX (left) and e.pageY (top). Based on this coordinates position the context menu absolutely.

Also, instead of coupling ContextMenu component's behavior with parent's state, display the ContextMenu component always (but hidden). Something like this

var ContextMenu = React.createClass({
    getInitialState: function(){
        return {contextMenuLocation: ''};
    },
    render: function() {
        var location = this.state.contextMenuLocation;
        var contentMenuStyle = {
            display: location ? 'block' : 'none',
            position: 'absolute', 
            left: location ? location.x : 0,
            top: location ? location.y : 0
        };
        return (
            <div id="results" style={contentMenuStyle}>
                Menu here
            </div>
        );
    }
});

Parent component's render would look like this

render: function(){
  return (<div>
    .....
    <ContextMenu ref="contextMenu" />
  </div>);
}

Maintain a reference to contextMenu in parent component

componentDidMount: function(){
  this.contextMenu = this.refs.contextMenu;
}

Display it like this

_onContextMenu: function(e) {
    this.contextMenu.setState({
      contextMenuLocation: {'x' : e.pageX, 'y': e.pageY}
    });
    return false;
}

Here is the updated demo http://jsfiddle.net/dhirajbodicherla/kb3gN/11383/

Upvotes: 8

Related Questions