Skip to content

Commit

Permalink
feat: allow overriding the selectedTab on Tabs component (#186)
Browse files Browse the repository at this point in the history
* allow overriding the selectedTab on Tabs component

* useControlledState

* remove unused import

* add onChange callback
  • Loading branch information
tbehailu committed Jan 22, 2024
1 parent adb81aa commit a0ad2d1
Showing 1 changed file with 13 additions and 5 deletions.
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

0 comments on commit a0ad2d1

Please sign in to comment.