From 9979d58d56a86270ac037b6d677b1a0d41b97463 Mon Sep 17 00:00:00 2001 From: Dani Guardiola Date: Thu, 8 Aug 2024 13:46:53 +0200 Subject: [PATCH] Add "scroll into view" behavior to selected tabs. --- packages/components/src/tabs/tablist.tsx | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/packages/components/src/tabs/tablist.tsx b/packages/components/src/tabs/tablist.tsx index 4906e0088417b7..764db255823169 100644 --- a/packages/components/src/tabs/tablist.tsx +++ b/packages/components/src/tabs/tablist.tsx @@ -27,15 +27,16 @@ export const TabList = forwardRef< const context = useTabsContext(); const selectedId = context?.store.useState( 'selectedId' ); - const indicatorPosition = useTrackElementOffsetRect( - context?.store.item( selectedId )?.element - ); + const selectedElement = context?.store.item( selectedId )?.element; + const indicatorPosition = useTrackElementOffsetRect( selectedElement ); const [ animationEnabled, setAnimationEnabled ] = useState( false ); - useOnValueUpdate( - selectedId, - ( { previousValue } ) => previousValue && setAnimationEnabled( true ) - ); + useOnValueUpdate( selectedId, ( { previousValue } ) => { + selectedElement?.scrollIntoView( { behavior: 'instant' } ); + if ( previousValue ) { + setAnimationEnabled( true ); + } + } ); if ( ! context ) { warning( '`Tabs.TabList` must be wrapped in a `Tabs` component.' );