Search code examples
reactjsevent-handlingparameter-passingpreventdefault

How to pass parameters to custom event listener and prevent default in reactjs?


I have to pass some argument to event handler and need to prevent default events. How to achieve this? By reactjs onMouseUp we can pass parameter but now because of passive events can't prevent default (eg: event.preventDefault();) But in case of custom event listener we can prevent default but not able to pass argument. Any solution will appreciable. Here is my code.

componentDidMount() {
    this.svgNode.current.addEventListener("mouseUp", this.mouseUpHandler, {
      passive: false,
    });
  }
mouseUpHandler(someParam, event) {
  event.preventDefault();
}

render() {
  let someParam = "somevalue";
  return () {
    <svg ref={this.svgNode} onMouseUp={this.mouseUpHandler.bind(this, someParam)} >
    /*some child nodes */
    </svg>
  }
}

Note: event.preventDefault() inside default event listener will cause error because target will treat as passive


Solution

  • You can use addEventHandler and pass already bound event handler with your custom parameter, for example:

    App.js

    import React, { Component } from "react";
    import "./styles.css";
    
    export default class App extends Component {
      svgNode;
      someParam = "somevalue";
    
      constructor(props) {
        super(props);
        this.svgNode = React.createRef();
        // if you need to access dynamic value use this
        this.mouseUpHandler = this.mouseUpHandler.bind(this, () => this.someParam);
    
        // uncomment if you need to access static value, which will not be modified, you can pass it directly
        // this.mouseUpHandler = this.mouseUpHandler.bind(this, this.someParam);
      }
    
      componentDidMount() {
        this.svgNode.current.addEventListener("mouseup", this.mouseUpHandler, {
          passive: false
        });
      }
    
      componentWillUnmount() {
        this.svgNode.current.removeEventListener("mouseup", this.mouseUpHandler);
      }
    
      mouseUpHandler(someParam, event) {
        console.log(someParam, event);
        event.preventDefault();
      }
    
      render() {
        return (
          <svg ref={this.svgNode}>
            <circle
              cx="50"
              cy="50"
              r="40"
              stroke="green"
              strokeWidth="4"
              fill="yellow"
            />
          </svg>
        );
      }
    }
    

    take a look at this codesandbox.