Lukáš Unzeitig
Lukáš Unzeitig

Reputation: 439

Issues in reactjs with event.which - undefined

I have event on canvas onMouseDown -

 <canvas id="myCanvas" width="150" height="150" onMouseMove={this.beginNewPatch.bind(this)}></canvas>

But when i move above canvas, i am trying to get now if left button on mouse is clicked with e.which, but this prints undefined. Any tips why?

beginNewPatch(e){
  console.log(e.which);
  if (e.which === 1) {
    let dot, eventDoc, doc, body, pageX, pageY;
    e = e  || window.event;
  }
}

Upvotes: 0

Views: 273

Answers (1)

soywod
soywod

Reputation: 4520

Try with event.button (see here from MDN) :

class App extends React.Component {
  constructor() {
    super();
    this.beginNewPatch = this.beginNewPatch.bind(this);
  }
  
  componentDidMount() {
    const ctx = this.refs.canvas.getContext('2d');
    ctx.fillRect(0,0, 100, 100);
  }
  
  beginNewPatch(event) {
    console.log(event.button);
  }
  
  render() {
    return (
      <canvas
        ref="canvas"
        width={100}
        height={100}
        onMouseDown={this.beginNewPatch}
      />
    );
  }
}

ReactDOM.render(
  <App />,
  document.getElementById('app')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="app"></div>

Upvotes: 1

Related Questions