Skip to content

Commit

Permalink
fix(performance): auto memoize TabList (#1449)
Browse files Browse the repository at this point in the history
  • Loading branch information
stipsan authored Nov 1, 2024
1 parent 05748bd commit 3713c2e
Showing 1 changed file with 3 additions and 11 deletions.
14 changes: 3 additions & 11 deletions src/core/components/tab/tabList.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import {cloneElement, forwardRef, useCallback, useMemo, useState} from 'react'
import {cloneElement, forwardRef, useCallback, useState, Children, isValidElement} from 'react'
import {styled} from 'styled-components'
import {Inline, InlineProps} from '../../primitives'

Expand All @@ -9,10 +9,6 @@ export interface TabListProps extends Omit<InlineProps, 'as' | 'height'> {
children: Array<React.ReactElement | null | undefined | false>
}

function _isReactElement(node: unknown): node is React.ReactElement {
return Boolean(node)
}

//Limits the width of tabs in tablist
const CustomInline = styled(Inline)`
& > div {
Expand All @@ -33,22 +29,18 @@ export const TabList = forwardRef(function TabList(
const {children: childrenProp, ...restProps} = props
const [focusedIndex, setFocusedIndex] = useState(-1)

const children = useMemo(() => childrenProp.filter(_isReactElement), [childrenProp])
const children: React.ReactElement[] = Children.toArray(childrenProp).filter(isValidElement)

const tabs = children.map((child, childIndex) =>
cloneElement(child, {
focused: focusedIndex === childIndex,
key: childIndex,
onFocus: () => handleTabFocus(childIndex),
onFocus: () => setFocusedIndex(childIndex),
}),
)

const numTabs = tabs.length

const handleTabFocus = useCallback((tabIdx: number) => {
setFocusedIndex(tabIdx)
}, [])

const handleKeyDown = useCallback(
(event: React.KeyboardEvent<HTMLDivElement>) => {
if (event.key === 'ArrowLeft') {
Expand Down

0 comments on commit 3713c2e

Please sign in to comment.