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

feat: allow overriding the selectedTab on Tabs component #186

Merged
merged 4 commits into from
Jan 22, 2024
Merged
Changes from all commits
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
18 changes: 13 additions & 5 deletions src/tabs/Tabs.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import React, {
useState,
Children,
cloneElement,
ReactNode,
isValidElement,
ReactElement,
HtmlHTMLAttributes,
} from 'react';
import { useControlledState } from '@react-stately/utils';
import { Text } from '../content';
import { css } from '@emotion/react';
import { Orientation } from '../types/orientation';
Expand Down Expand Up @@ -112,6 +112,10 @@ function parseTabList(children: ReactNode): Tab[] {
export type TabsProps = {
children: ReactNode[];
className?: string;
/**
* If specified, the index of the selected tab is controlled by the parent component rather than the internal state.
*/
index?: number;
onChange?: (index: number) => void;
/**
* The orientation of the tabs. Defaults to horizontal
Expand All @@ -127,16 +131,21 @@ export type TabsProps = {
export function Tabs({
children,
className,
index,
onChange,
orientation = 'horizontal',
extra,
}: TabsProps) {
// Filter out the nulls from the children so that tabs can be mounted conditionally
children = Children.toArray(children).filter(child => child);
const tabs = parseTabList(children);
// Initialize the selected tab to the first non-hidden tab
const [selectedIndex, setSelectedIndex] = useState<number>(
tabs.findIndex(tab => !tab.hidden)

// Initialize the selected tab to the first non-hidden tab if there is no controlled value provided
const defaultValue = tabs.findIndex(tab => !tab.hidden);
const [selectedIndex, setSelectedIndex] = useControlledState(
index,
defaultValue,
onChange
);
return (
<div
Expand All @@ -159,7 +168,6 @@ export function Tabs({
onClick={e => {
e.preventDefault();
setSelectedIndex(index);
onChange && onChange(index);
}}
{...tab?.tabListItemProps}
>
Expand Down
Loading