Skip to content

Commit b36e23c

Browse files
author
ugogo
committed
remove activeIndex when clicking outside
1 parent eb1c7c2 commit b36e23c

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

src/index.tsx

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@ const KEY_CODE = {
88
DELETE: 46,
99
};
1010

11+
const CONTAINER_DATA_ID = 'REACT_VERIFICATION_CODE_CONTAINER';
12+
1113
export default ({ length = 4, placeholder = '·' }) => {
1214
const [activeIndex, setActiveIndex] = React.useState<number>(-1);
1315
const [value, setValue] = React.useState<string[]>(
@@ -87,8 +89,29 @@ export default ({ length = 4, placeholder = '·' }) => {
8789
blurItem(activeIndex);
8890
};
8991

92+
React.useEffect(() => {
93+
const onDocumentClick = (e: MouseEvent) => {
94+
const targetIncludesContainer = e
95+
.composedPath()
96+
.reduce(
97+
(bool: boolean, path: HTMLElement) =>
98+
bool || path.dataset?.reactVerificationCodeId === CONTAINER_DATA_ID,
99+
false
100+
);
101+
102+
if (!targetIncludesContainer) setActiveIndex(-1);
103+
};
104+
105+
document.addEventListener('click', onDocumentClick);
106+
107+
return () => {
108+
document.removeEventListener('click', onDocumentClick);
109+
};
110+
}, []);
111+
90112
return (
91113
<div
114+
data-react-verification-code-id={CONTAINER_DATA_ID}
92115
className='ReactVerificationCode__container'
93116
style={
94117
{

0 commit comments

Comments
 (0)