onClick on a link don't seem to work


#1

Hi,

I have FlowRouter for my Meteor’s routing. And I use React.

I will going crazy with my bug.

I have a simple component with a link balise :

<a href="/somePath" onClick={this.onClick.bind(this)} key={artwork._id}> Link </a>

And my onClick function is :

onClick(e){
  e.preventDefault();
}

It’s very basic… so I want to prevent the click on the link… a very common feature.

BUT it doesn’t work !
On the left click, FlowRouter go the /somePath route. On the middle click, the preventDefault() works.
On the right click, the link is open in the new tab.

I don’t want the left click to go to the route, I want to open a modal with some content. And I want to have the right click which open the link on the new tab.

What’s the hell is going on ?

Have you got some explanation ?

Thx.


#2

This has been previously discussed in a few places:

This is an issue with Flow Router (or more specifically Page.js which it uses behind the scenes). You might want to consider removing the href from your link, and handling your routing call via your onClick handler. Another option is to consider switching to React Router (where this does work properly).


#3

Hi @hwillson

I want to use Flow Router… If I remove the href from the link, how user can’t open it in a new tab ? :confused:


#4

What do you want to achieve? Should the link still work? What should happen if a user clicks the link?


#5

You know https://dribbble.com/ ?

When you click on a design, a modal with the content of the design is contened.
The url change but the user stay on the same page.

When you right click on a design, and your open a new tab, you are redirect to the single page of this design.

All of this are handle in my application. But only the left click doesn’t work like i said before.

For the moment, my href is ‘/’ to stay on the home page and show modal. But with right click, user is redirected to the home page, and not to the single page…


#6

You could just fall back on plain old javascript:

import React, { Component } from 'react';

export default class SomeComponent extends Component {
  constructor(props) {
    super(props);
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick(event) {
    event.preventDefault();
    const mouseClick = event.nativeEvent.which;
    if (mouseClick === 1) {
      // Left mouse click - open in modal ...
    } else if (mouseClick === 3) {
      // Right mouse click - open in new tab ...
      window.open('some url');
    }
  }

  render() {
    return (
      <div className="some-component">
        <a onClick={this.handleClick} onContextMenu={this.handleClick}>
          Some Link
        </a>
      </div>
    );
  }
};


#7

Awesome @hwillson !
It’s works.

But, the onContextMenu is not so good :confused:
User can’t copy link etc…


#8

I going to switching to React Router…
It’s just, with Flow Router, with have some support for Fast Render… and other features I thinks :confused: