I have a <Link>
element from React Router that I don't want to open in a new tab or existing tab, but e.preventDefault()
isn't working:
constructor(props) {
super(props);
this.loadLink = this.loadLink.bind(this);
}
loadLink(e) {
e.preventDefault();
const id = null || e.target.id;
this.props.onLink(id);
}
render() {
return (
<Link id="my-id" ref="my-id" onClick={this.loadLink} to="/some-url">Some link</Link>
);
}
I've tried e.stopPropagation()
and e.nativeEvent.stopImmediatePropagation()
, tried converting it from <Link>
to a regular <a>
tag, but no matter what clicking the link always opens in a new tab.
I've checked via dev tools and it's the only custom event handler attached to that link.
Any ideas what this could be or how to trace?
OK, it turns out someone else had added a function to add event listeners to all hrefs in another component, which is why it was opening in a new tab no matter what I did.
componentDidMount() {
const anchors = document.getElementsByTagName("a");
for (let i = 0, length = anchors.length; i < length; i++) {
const anchor = anchors[i];
anchor.addEventListener('click', function(e) {
e.preventDefault();
window.open(this.getAttribute('href'), '_blank');
}, true);
}
}
Removing this fixed this issue.
One lesson is to limit scope of functions to component level only, the above function governed all hrefs in all components, not just the one it was written in.
It was listened in the click event handlers of the dev tools inspector, I just mistakenly assumed it referred to something else.