1

I want to run some tracking code when user clicks a button in my react project. However on click handler doesn't executed if user open it in a new tab.

Is there any solution for it in React js.

Simple example:

var Hello = React.createClass({
    render: function() {
        function click(event) {
            event.preventDefault();
            console.log('You can see me even is user clicked on "open link in new tab"')
        }
        return <div >
            < a href = '#'
        target = "_blank"
        onClick = { click } > Go there < /a> < /div>;
    }
});

React.render( < Hello / > , document.body);
Ilya Vinokurov
  • 145
  • 2
  • 12
  • why you want to put the handle inside render function ? – VISHAL DAGA Sep 26 '16 at 19:31
  • I think your code does work. I've put it in a [jsfiddle](https://jsfiddle.net/normanganderson/wk6fjdp9/). Open up your console and you'll see the message get logged. – CallMeNorm Sep 26 '16 at 20:15

1 Answers1

0

This should work fine -

  const Hello =  React.createClass({

          click(event) {
                    //here this is the component
                    event.preventDefault();
                    console.log('You can see me even is user clicked on "open link in new tab"')
          },

          render() {
           return <div >
                    < a href = '#'
                target = "_blank"
                onClick = { this.click ///or this.click.bind(this) if you want to have this point to the component } > Go there < /a> < /div>;
          }
  });
VISHAL DAGA
  • 4,132
  • 10
  • 47
  • 53
  • This won't work because `click` is undefined the way you're using it. You'll need to do `this.click` in the render function. – CallMeNorm Sep 26 '16 at 20:02
  • thank you, but if you right click on your mouse and click "open link in new tab" it will not execute the "click". This is my problem! – Ilya Vinokurov Sep 27 '16 at 20:05
  • see there is no event when user click on "open link in new tab". However you can use mousedown insted of cick event and find if the click is from right mouse button. some hacks mentioned here - http://stackoverflow.com/questions/2578092/jquery-click-handler-is-not-invoked-when-link-is-opened-in-new-tab-window – VISHAL DAGA Sep 28 '16 at 10:44