tomasnikl
tomasnikl

Reputation: 103

React onClick method od link with href not working

In my React app, I have links with href attribute (it is need to open links in new window after right click on link) and on link element is react onClick method.

See example here:

class SomeComponent extends React.Component { 
  handleClick(event) {
  	alert('click. but dont redirect...');
    
    return false;
    event.preventDefault();
    event.stopPropagation();
  }
  render() {
    return (
      <a href="test" onClick={this.handleClick}>Test link</a>
    );
  }
}

ReactDOM.render(<SomeComponent/>, document.getElementById('container'));
<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="container">
</div>

click on link. onClick method calls, it is ok, but browser do redirect to page, in href attribute and I don't know, how can I prevent it.

Is possible have link with href attribute and onclick method in React without redirect on to the page in href attr?

Fiddle.

Upvotes: 2

Views: 10059

Answers (3)

Fernando Francis
Fernando Francis

Reputation: 3

remove preventDefault(); from onClick

Upvotes: 0

Shahzad
Shahzad

Reputation: 131

You are almost there !!!! You just need to move

event.preventDefault();
event.stopPropagation();

up. And it will work !!!!.

Please find below code . Paste it.

class SomeComponent extends React.Component { 
  handleClick(event) {
    event.preventDefault();
    event.stopPropagation();
    alert('click. but dont redirect...');

    return false;

  }
  render() {
    return (
      <a href="test" onClick={this.handleClick}>Test link</a>
    );
  }
}

ReactDOM.render(<SomeComponent/>, document.getElementById('container'));

Upvotes: 2

Jamesed
Jamesed

Reputation: 302

in your href try using "javascript:void(0);"

Upvotes: 0

Related Questions