Reputation: 103
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?
Upvotes: 2
Views: 10059
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