Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Tabs: Fallback to first enabled tab if no active tab Id #60681

Merged
merged 5 commits into from
Apr 12, 2024
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 9 additions & 6 deletions packages/components/src/tabs/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,14 @@ function Tabs( {
}
}, [ isControlled, selectedTab, selectedTabId, setSelectedId ] );

useEffect( () => {
// If there is no active tab, fallback to place focus on the first enabled tab
// so there is always an active element
if ( selectedTabId === null && ! activeId && firstEnabledTab?.id ) {
setActiveId( firstEnabledTab.id );
}
}, [ selectedTabId, activeId, firstEnabledTab?.id, setActiveId ] );
Comment on lines +156 to +162
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I feel like it'd be safer to move this out to a designated effect like so, instead of piggybacking on another one. I'd want to avoid unintended complications down the line. In that vein, I think we'd be safer to add a selectedTabId === null condition, since that's the only time we need this logic, as far as we know. (And it doubles as a isControlled check.)

Does that sound reasonable? Anything I'm missing?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was considering this too from a code readability standpoint. I wasn't sure performance and debugging-wise if it would be worse to add another useEffect though. I'm totally fine with this route though if you are!


useEffect( () => {
if ( ! isControlled ) {
return;
Expand All @@ -166,11 +174,6 @@ function Tabs( {
! focusedElement ||
! items.some( ( item ) => focusedElement === item.element )
) {
// If there is no focused or active tab, fallback to place focus on the first enabled tab
// so there is always an active element
if ( ! activeId && firstEnabledTab?.id ) {
setActiveId( firstEnabledTab.id );
}
return;
}

Expand All @@ -182,7 +185,7 @@ function Tabs( {
setActiveId( focusedElement.id );
}
} );
}, [ activeId, isControlled, items, setActiveId, firstEnabledTab ] );
}, [ activeId, isControlled, items, setActiveId ] );

const contextValue = useMemo(
() => ( {
Expand Down