We need to trigger a function when our website users click on a button (for Mixpanel analytics). Is it a good idea to just update our Gatsby Link components with an onClick handler?
I'm particularly mindful of accessibility issues.
Thanks
// What we currently do
const Component = () => {
return <Link to="/">Home</Link>
}
// What we're thinking of doing
const Component = () => {
const handleClick = (e) => {
e.preventDefault();
triggerFunction();
navigate("/")
}
return <Link to="/" onClick={handleClick}>Home</Link>
}
It sounds like adding the onClick would work better for us than using onRouteUpdate (as we need to specifically know the button that was clicked). To clarify, using onClick on a Link is valid syntax? And we don't need to do any sort of work to delay the page change to be sure that the onClick fires and completes before the page change?
It's not a good idea using Gatsby's Link
component to change and prevent its default behavior. It can lead to some inconsistencies and undesired behavior.
As you pointed out, onRouteUpdate
would be the cleanest solution so far, but if it's not an option, I'd say it's preferable to use a regular <div>
(or another tag) to make the navigation. To me, it doesn't make sense to use a Link
and change completely its behavior to perform some actions before the main action (preventing it and navigating through navigate()
function) because you are not taking any advantage of using it.
I like the idea of using your own custom navigation component but not using a Link
which it won't behave as Link
.
const Component = () => {
const handleClick = (e) => {
e.preventDefault();
triggerFunction();
navigate("/")
}
return <a href="/" onClick={handleClick}>Home</a>
}