Reputation: 11
import React from 'react';
class Anchor extends React.Component {
onClick = (event) => {
// -----------------------------
// send Google Analytics request 👌
// -----------------------------
if (this.props.onClick) {
this.props.onClick(event);
}
}
render () {
return <a {...this.props} onClick={this.onClick} />;
}
}
export default Anchor;
const test1 = <Anchor href="https://www.google.com" />
// 👆 not work - did not send Google Analytics request - but open "href"
Easy solution you think? Just add event.preventDefault()
to onClick
function? Ok imagine we added that...
const test2 = <Anchor href="https://www.google.com" onClick=((e) => console.log(e)) />
it send Google Analytics request because we added event.preventDefault()
but it did not open href
Upvotes: 1
Views: 231
Reputation: 560
You can simply use event.preventDefault()
in your onClick. Then do your request wait for response and set your href via window.location.href="https://www.google.com";
Example:
<a href="https://www.google.com" onClick={e =>{ e.preventDefault(); console.log("do your stuff..."); window.location.href="https://www.google.com"; }}>test</a>
Or am I missing something?
Upvotes: 1