Skip to content

Commit 2dd57f1

Browse files
RobinMalfaitRyogaK
andauthored
Improve controlled Tabs behaviour (#1050)
* Append tests for Tab.Group's selectedIndex. * ensure that we correctly use the incoming selectedIndex * update changelog Co-authored-by: Ryoga Kitagawa <[email protected]>
1 parent a371976 commit 2dd57f1

File tree

4 files changed

+17
-0
lines changed

4 files changed

+17
-0
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
1010
### Fixed
1111

1212
- Ensure correct order when conditionally rendering `Menu.Item`, `Listbox.Option` and `RadioGroup.Option` ([#1045](https://github.com/tailwindlabs/headlessui/pull/1045))
13+
- Improve controlled Tabs behaviour ([#1050](https://github.com/tailwindlabs/headlessui/pull/1050))
1314

1415
## [Unreleased - @headlessui/vue]
1516

packages/@headlessui-react/src/components/tabs/tabs.test.tsx

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -551,6 +551,12 @@ describe('Rendering', () => {
551551
// test controlled behaviour
552552
await click(getByText('setSelectedIndex'))
553553
assertTabs({ active: 2 })
554+
555+
// test uncontrolled behaviour again
556+
await click(getByText('Tab 2'))
557+
expect(handleChange).toHaveBeenCalledTimes(2)
558+
expect(handleChange).toHaveBeenNthCalledWith(2, 1)
559+
assertTabs({ active: 1 })
554560
})
555561

556562
it('should jump to the nearest tab when the selectedIndex is out of bounds (-2)', async () => {

packages/@headlessui-react/src/components/tabs/tabs.tsx

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -202,6 +202,10 @@ function Tabs<TTag extends ElementType = typeof DEFAULT_TABS_TAG>(
202202
}, [defaultIndex, selectedIndex, state.tabs, state.selectedIndex])
203203

204204
let lastChangedIndex = useRef(state.selectedIndex)
205+
useEffect(() => {
206+
lastChangedIndex.current = state.selectedIndex
207+
}, [state.selectedIndex])
208+
205209
let providerBag = useMemo<ContextType<typeof TabsContext>>(
206210
() => [
207211
state,

packages/@headlessui-vue/src/components/tabs/tabs.test.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -579,6 +579,12 @@ describe('`selectedIndex`', () => {
579579
// test controlled behaviour
580580
await click(getByText('setSelectedIndex'))
581581
assertTabs({ active: 2 })
582+
583+
// test uncontrolled behaviour again
584+
await click(getByText('Tab 2'))
585+
expect(handleChange).toHaveBeenCalledTimes(2)
586+
expect(handleChange).toHaveBeenNthCalledWith(2, 1)
587+
assertTabs({ active: 1 })
582588
})
583589

584590
it('should jump to the nearest tab when the selectedIndex is out of bounds (-2)', async () => {

0 commit comments

Comments
 (0)