React OnMouseDown event is not working whereas OnMouseUp is working fine.(on SVG elements)
Asked Answered
J

2

5

I am having an svg element on which I need to capture the mousedown event. Here is the code.

//code snippet...
<g onMouseDown={this.clickHandler}>
    <circle ...></circle>
    <text> </text>
</g>

Code for click handler is as simple as this.

clickHandler() {
    alert("mouse down")
 }

onMouseUp and OnClick are working fine, but not the onMouseDown

The same onMouseDown event in working fine outside the SVG (I tried on Button)

Any Idea about the error.

React Version: 16.5.2

Jeb answered 12/12, 2018 at 12:14 Comment(3)
onClick is equal to onMouseUp + onMouseDown.Why are you using them all?Solidago
@Root, there are some operations I want to perform when the element in mouse press and some operation as soon as the mouse button is released.Jeb
Could you post a full example? This minimal example works as expected: codesandbox.io/s/lrz0kr87klOl
J
6

OnMouseDown will get a block if you are also having the drag functionality implemented.

To capture the OnMouseDown you need to remove event.stopPropogation() from your dragStartEvent

Another Interesting thing is if you don't want to remove event.stopPropogation() you can still perform the all the operation which you intend to perform on OnMouseDown in dragStartEvent event.

Hope this helps...

Jeb answered 14/12, 2018 at 10:50 Comment(0)
E
3
class Hello extends React.Component {
  onDown() {
    console.log("Down");
  }
  onClick() {
    console.log("Click");
  }

  render() {
    return (
      <div>
        <svg >
          <g onClick={this.onClick} onMouseDown={this.onDown} >
            <circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" />
          </g>
        </svg>
      </div>
    );
  }
}

ReactDOM.render(
  <Hello name="World" />,
  document.getElementById('container')
);

Working fine with console.log link

Electromotor answered 12/12, 2018 at 13:19 Comment(2)
I think there is a typo: should stroke-width be strokeWidth ? Here is a CodeSandbox link of a slightly modified version of the above code running in an online repl. (code is in App.js, Click "console" below the output box in order to see content of the Console.)Efthim
(I reverted theprevious edit: it changed the code itself, introducing syntax errors - it changed the html tags, probably by accident. Then edited to fix indentation, also wrapping the return html in () so opening div tag could be moved to next line, and all html tags could then be lined up for clarity - it's the standard way to return React/HTML code.)Efthim

© 2022 - 2024 — McMap. All rights reserved.