Skip to content

Commit 1085db5

Browse files
author
ugogo
committed
use input.onblur rather than document.click to blur items
1 parent 910624a commit 1085db5

File tree

1 file changed

+9
-28
lines changed

1 file changed

+9
-28
lines changed

src/index.tsx

+9-28
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,6 @@ const KEY_CODE = {
88
DELETE: 46,
99
};
1010

11-
const CONTAINER_DATA_ID = 'REACT_VERIFICATION_CODE_CONTAINER';
12-
1311
export default ({ length = 4, placeholder = '·' }) => {
1412
const [activeIndex, setActiveIndex] = React.useState<number>(-1);
1513
const [value, setValue] = React.useState<string[]>(
@@ -34,7 +32,7 @@ export default ({ length = 4, placeholder = '·' }) => {
3432
if (codeInputRef.current) codeInputRef.current.focus();
3533
};
3634

37-
const onItemKeyUp = ({ key, keyCode }: React.KeyboardEvent) => {
35+
const onInputKeyUp = ({ key, keyCode }: React.KeyboardEvent) => {
3836
const newValue = [...value];
3937
const nextIndex = activeIndex + 1;
4038
const prevIndex = activeIndex - 1;
@@ -81,7 +79,7 @@ export default ({ length = 4, placeholder = '·' }) => {
8179
setActiveIndex(-1);
8280
};
8381

84-
const onItemChange = (e: React.ChangeEvent<HTMLInputElement>) => {
82+
const onInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
8583
const { value: changeValue } = e.target;
8684
const isCode = isCodeRegex.test(changeValue);
8785

@@ -90,31 +88,13 @@ export default ({ length = 4, placeholder = '·' }) => {
9088
blurItem(activeIndex);
9189
};
9290

93-
React.useEffect(() => {
94-
const onDocumentClick = (e: MouseEvent) => {
95-
const targetIncludesContainer = e.composedPath().reduce(
96-
(bool: boolean, path: EventTarget) =>
97-
bool ||
98-
// @to-do: find which type to use
99-
// to make it compatible with dataset
100-
// @ts-ignore
101-
path.dataset?.reactInputVerificationCodeId === CONTAINER_DATA_ID,
102-
false
103-
);
104-
105-
if (!targetIncludesContainer) setActiveIndex(-1);
106-
};
107-
108-
document.addEventListener('click', onDocumentClick);
109-
110-
return () => {
111-
document.removeEventListener('click', onDocumentClick);
112-
};
113-
}, []);
91+
const onInputBlur = () => {
92+
setActiveIndex(-1);
93+
blurItem(activeIndex);
94+
};
11495

11596
return (
11697
<div
117-
data-react-input-verification-code-id={CONTAINER_DATA_ID}
11898
className='ReactInputVerificationCode__container'
11999
style={
120100
{
@@ -136,8 +116,9 @@ export default ({ length = 4, placeholder = '·' }) => {
136116
// use onKeyUp rather than onChange for a better control
137117
// onChange is still needed to handle the autocompletion
138118
// when receiving a code by SMS
139-
onChange={onItemChange}
140-
onKeyUp={onItemKeyUp}
119+
onChange={onInputChange}
120+
onKeyUp={onInputKeyUp}
121+
onBlur={onInputBlur}
141122
/>
142123

143124
{itemsRef.map((ref, i) => (

0 commit comments

Comments
 (0)