React component for tracking clicks on external links with automatic gtag event firing and intelligent navigation handling.
Enhanced anchor component that automatically tracks outbound link clicks as gtag events.
import * as React from "react";
/**
* OutboundLink component that tracks external link clicks
* Extends standard HTML anchor element with automatic event tracking
* Implemented as a React.forwardRef for ref forwarding support
*/
declare const OutboundLink: React.ForwardRefExoticComponent<
OutboundLinkProps & React.HTMLProps<HTMLAnchorElement> & React.RefAttributes<HTMLAnchorElement>
>;
interface OutboundLinkProps {
/** Optional click handler called before gtag event tracking */
onClick?: (event: React.MouseEvent<HTMLAnchorElement>) => void;
}Usage Examples:
import React from "react";
import { OutboundLink } from "gatsby-plugin-google-gtag";
export default function ExternalLinks() {
return (
<div>
<OutboundLink href="https://example.com">
Visit Example Site
</OutboundLink>
<OutboundLink
href="https://docs.example.com"
target="_blank"
rel="noopener noreferrer"
>
View Documentation
</OutboundLink>
</div>
);
}import React from "react";
import { OutboundLink } from "gatsby-plugin-google-gtag";
export default function TrackedLinks() {
const handleLinkClick = (event) => {
console.log("Custom click logic before tracking");
// Custom logic here - gtag tracking happens automatically after
};
return (
<OutboundLink
href="https://partner-site.com"
onClick={handleLinkClick}
>
Partner Site
</OutboundLink>
);
}import React, { useRef } from "react";
import { OutboundLink } from "gatsby-plugin-google-gtag";
export default function RefExample() {
const linkRef = useRef(null);
const focusLink = () => {
linkRef.current?.focus();
};
return (
<div>
<OutboundLink
ref={linkRef}
href="https://example.com"
>
External Link
</OutboundLink>
<button onClick={focusLink}>Focus Link</button>
</div>
);
}The OutboundLink component automatically fires a gtag event when clicked:
window.gtag("event", "click", {
event_category: "outbound",
event_label: href, // The target URL
transport_type: redirect ? "beacon" : "",
event_callback: function () {
if (redirect) {
document.location = href;
}
},
});The component intelligently handles navigation based on user behavior:
target is not _selfpreventDefault() from custom click handlersThe component validates props during development:
OutboundLink.propTypes = {
href: PropTypes.string,
target: PropTypes.string,
onClick: PropTypes.func,
};OutboundLink accepts all standard HTML anchor element props:
href, target, rel, downloadclassName, style, idaria-* attributes for accessibilityonMouseOver, onFocus, etc.The component forwards all props to the underlying <a> element while adding tracking behavior.