Skip to content

Commit bc465bb

Browse files
committed
feat(CModal): restore focus to the previously focused element once the modal is hidden
1 parent 306346a commit bc465bb

File tree

1 file changed

+7
-0
lines changed
  • packages/coreui-react/src/components/modal

1 file changed

+7
-0
lines changed

packages/coreui-react/src/components/modal/CModal.tsx

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,7 @@ export const CModal = forwardRef<HTMLDivElement, CModalProps>(
111111
},
112112
ref,
113113
) => {
114+
const activeElementRef = useRef<HTMLElement | null>(null)
114115
const modalRef = useRef<HTMLDivElement>(null)
115116
const modalContentRef = useRef<HTMLDivElement>(null)
116117
const forkedRef = useForkedRef(ref, modalRef)
@@ -129,8 +130,13 @@ export const CModal = forwardRef<HTMLDivElement, CModalProps>(
129130

130131
useEffect(() => {
131132
if (_visible) {
133+
activeElementRef.current = document.activeElement as HTMLElement | null
132134
document.addEventListener('mouseup', handleClickOutside)
133135
document.addEventListener('keydown', handleKeyDown)
136+
} else {
137+
if (activeElementRef.current) {
138+
activeElementRef.current.focus()
139+
}
134140
}
135141

136142
return () => {
@@ -145,6 +151,7 @@ export const CModal = forwardRef<HTMLDivElement, CModalProps>(
145151
}
146152

147153
setVisible(false)
154+
148155
return onClose && onClose()
149156
}
150157

0 commit comments

Comments
 (0)