From 020b1adf79fa316bb909b5fe3f87ab6fed13dbfd Mon Sep 17 00:00:00 2001 From: Gilles De Mey Date: Tue, 21 Nov 2023 13:01:29 +0100 Subject: [PATCH] UI: Fix tab href race condition (#78458) prevent tab clicking from activating the anchor's href This prevents a very rare race condition when switching tabs very fast or when switching between tabs that update shortly after initial render. --- packages/grafana-ui/src/components/Tabs/Tab.tsx | 10 +++++++++- packages/grafana-ui/src/components/Tabs/Tabs.story.tsx | 8 ++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/packages/grafana-ui/src/components/Tabs/Tab.tsx b/packages/grafana-ui/src/components/Tabs/Tab.tsx index 7d1309f9d95..a867eec8bd4 100644 --- a/packages/grafana-ui/src/components/Tabs/Tab.tsx +++ b/packages/grafana-ui/src/components/Tabs/Tab.tsx @@ -39,6 +39,14 @@ export const Tab = React.forwardRef( const linkClass = cx(tabsStyles.link, active ? tabsStyles.activeStyle : tabsStyles.notActive); + // wraps the onClick handler with "event.preventDefault" – prevents a rare race condition between navigating to the "href" and "onClick" handler + const onClickHandler = onChangeTab + ? (event: React.MouseEvent) => { + event.preventDefault(); + onChangeTab(event); + } + : () => {}; + return (
( href={href ? href : '#'} className={linkClass} {...otherProps} - onClick={onChangeTab} + onClick={onClickHandler} aria-label={otherProps['aria-label'] || selectors.components.Tab.title(label)} role="tab" aria-selected={active} diff --git a/packages/grafana-ui/src/components/Tabs/Tabs.story.tsx b/packages/grafana-ui/src/components/Tabs/Tabs.story.tsx index 0f245028228..6125e3872ad 100644 --- a/packages/grafana-ui/src/components/Tabs/Tabs.story.tsx +++ b/packages/grafana-ui/src/components/Tabs/Tabs.story.tsx @@ -51,6 +51,14 @@ export const Simple: Story = () => { ); }; +export const withHref: Story = () => ( + + + + + +); + export const Counter: Story = (args) => { return ; };