Skip to content

Commit

Permalink
refactor(CSidebarNav): improve navigation
Browse files Browse the repository at this point in the history
  • Loading branch information
mrholek committed Dec 20, 2023
1 parent 2652a91 commit d85624f
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 8 deletions.
18 changes: 11 additions & 7 deletions packages/coreui-react/src/components/sidebar/CSidebarNav.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import React, {
ElementType,
forwardRef,
HTMLAttributes,
ReactElement,
ReactNode,
useState,
} from 'react'
Expand Down Expand Up @@ -31,31 +32,34 @@ interface ContextProps {

export const CNavContext = createContext({} as ContextProps)

const recursiveClone = (children: ReactNode, id?: string): ReactNode => {
const recursiveClone = (children: ReactNode, id?: string, updateId?: boolean): ReactNode => {
return React.Children.map(children, (child: ReactNode, index: number) => {
const _id = id ? `${id}.${index}` : `${index}`

if (!React.isValidElement(child)) {
return child
}

const _id = id ? (updateId ? `${id}.${index}` : `${id}`) : `${index}`

if (child.props && child.props.children) {
child = React.cloneElement(child, {
// @ts-expect-error the `displayName` exist in each component. TODO: resolve
...((child.type.displayName === 'CNavGroup' || child.type.displayName === 'CNavLink') && {
idx: _id,
test: _id,
}),
// @ts-expect-error the `children` exist in each component. TODO: resolve
children: recursiveClone(child.props.children, _id),
children: recursiveClone(
child.props.children,
_id,
// @ts-expect-error the `displayName` exist in each component. TODO: resolve
child.type.displayName === 'CNavItem' ? false : true,
),
})
}

return React.cloneElement(child as React.ReactElement<any>, {
return React.cloneElement(child as ReactElement<any>, {
// @ts-expect-error the `displayName` exist in each component. TODO: resolve
...((child.type.displayName === 'CNavGroup' || child.type.displayName === 'CNavLink') && {
idx: _id,
test: _id,
}),
})
})
Expand Down
2 changes: 1 addition & 1 deletion packages/docs/src/components/SidebarNav.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ export const SidebarNav = ({ items }: SidebarNavProps) => {
const navGroup = (item: NavItem, index: number) => {
const { name, icon, ...rest } = item
return (
<CNavGroup compact toggler={navLink(name, icon)} idx={String(index)} key={index} {...rest}>
<CNavGroup compact toggler={navLink(name, icon)} key={index} {...rest}>
{item.items?.map((item: NavItem, index: number) =>
item.items ? navGroup(item, index) : navItem(item, index),
)}
Expand Down

0 comments on commit d85624f

Please sign in to comment.