Skip to content

Commit 261ff5b

Browse files
committed
refactor(CSidebar): improve responsive behavior
1 parent 2955637 commit 261ff5b

File tree

1 file changed

+23
-9
lines changed

1 file changed

+23
-9
lines changed

packages/coreui-react/src/components/sidebar/CSidebar.tsx

Lines changed: 23 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -74,24 +74,29 @@ export const CSidebar = forwardRef<HTMLDivElement, CSidebarProps>(
7474
) => {
7575
const sidebarRef = useRef<HTMLDivElement>(null)
7676
const forkedRef = useForkedRef(ref, sidebarRef)
77-
const [mobile, setMobile] = useState(false)
78-
const [_visible, setVisible] = useState(visible)
77+
7978
const [inViewport, setInViewport] = useState<boolean>()
79+
const [mobile, setMobile] = useState(false)
80+
const [visibleMobile, setVisibleMobile] = useState(false)
81+
const [visibleDesktop, setVisibleDesktop] = useState(true)
8082

8183
useEffect(() => {
8284
sidebarRef.current && setMobile(isOnMobile(sidebarRef.current))
83-
84-
setVisible(visible)
85+
if (visible !== undefined) {
86+
handleVisibleChange(visible)
87+
}
8588
}, [visible])
8689

90+
91+
8792
useEffect(() => {
8893
inViewport !== undefined && onVisibleChange && onVisibleChange(inViewport)
8994
!inViewport && onHide && onHide()
9095
inViewport && onShow && onShow()
9196
}, [inViewport])
9297

9398
useEffect(() => {
94-
mobile && visible && setVisible(false)
99+
mobile && setVisibleMobile(false)
95100
}, [mobile])
96101

97102
useEffect(() => {
@@ -119,8 +124,17 @@ export const CSidebar = forwardRef<HTMLDivElement, CSidebarProps>(
119124
}
120125
})
121126

127+
const handleVisibleChange = (visible: boolean) => {
128+
if (mobile) {
129+
setVisibleMobile(visible)
130+
return
131+
}
132+
133+
setVisibleDesktop(visible)
134+
}
135+
122136
const handleHide = () => {
123-
setVisible(false)
137+
handleVisibleChange(false)
124138
}
125139

126140
const handleResize = () => {
@@ -167,8 +181,8 @@ export const CSidebar = forwardRef<HTMLDivElement, CSidebarProps>(
167181
[`sidebar-${position}`]: position,
168182
[`sidebar-${size}`]: size,
169183
'sidebar-narrow-unfoldable': unfoldable,
170-
show: _visible === true && mobile,
171-
hide: _visible === false && !mobile,
184+
show: (mobile && visibleMobile) || (overlaid && visibleDesktop),
185+
hide: !visibleDesktop && !mobile,
172186
},
173187
className,
174188
)}
@@ -180,7 +194,7 @@ export const CSidebar = forwardRef<HTMLDivElement, CSidebarProps>(
180194
{typeof window !== 'undefined' &&
181195
mobile &&
182196
createPortal(
183-
<CBackdrop className="sidebar-backdrop" visible={_visible} />,
197+
<CBackdrop className="sidebar-backdrop" visible={mobile && visibleMobile} />,
184198
document.body,
185199
)}
186200
</>

0 commit comments

Comments
 (0)