Skip to content

Commit

Permalink
useControlledState
Browse files Browse the repository at this point in the history
  • Loading branch information
tbehailu committed Jan 22, 2024
1 parent 49fd73e commit 3477600
Showing 1 changed file with 10 additions and 7 deletions.
17 changes: 10 additions & 7 deletions src/tabs/Tabs.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import React, {
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 @@ -115,7 +116,7 @@ export type TabsProps = {
/**
* If specified, the index of the selected tab is controlled by the parent component rather than the internal state.
*/
selectedTabIndex?: number;
index?: number;
onChange?: (index: number) => void;
/**
* The orientation of the tabs. Defaults to horizontal
Expand All @@ -131,20 +132,22 @@ export type TabsProps = {
export function Tabs({
children,
className,
selectedTabIndex,
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 [selectedStateIndex, 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,
() => {}
);
const selectedIndex =
typeof selectedTabIndex == "number" ? selectedTabIndex : selectedStateIndex;
return (
<div
className={`ac-tabs ${className}`}
Expand Down

0 comments on commit 3477600

Please sign in to comment.