Skip to content

Commit 5e41208

Browse files
Pedro Guerreironecolas
Pedro Guerreiro
authored andcommittedSep 19, 2023
[fix] TextInput cursor position with secureTextEntry
On web, the cursor jumps to the start of the input when secureTextEntry is toggled. Preserve and restore previous selection after secureTextEntry is toggled. Close #2576
1 parent 67a0bde commit 5e41208

File tree

1 file changed

+22
-10
lines changed
  • packages/react-native-web/src/exports/TextInput

1 file changed

+22
-10
lines changed
 

‎packages/react-native-web/src/exports/TextInput/index.js

+22-10
Original file line numberDiff line numberDiff line change
@@ -193,6 +193,15 @@ const TextInput: React.AbstractComponent<
193193

194194
const dimensions = React.useRef({ height: null, width: null });
195195
const hostRef = React.useRef(null);
196+
const prevSelection = React.useRef(null);
197+
const prevSecureTextEntry = React.useRef(false);
198+
199+
React.useEffect(() => {
200+
if (hostRef.current && prevSelection.current) {
201+
setSelection(hostRef.current, prevSelection.current);
202+
}
203+
prevSecureTextEntry.current = secureTextEntry;
204+
}, [secureTextEntry]);
196205

197206
const handleContentSizeChange = React.useCallback(
198207
(hostNode) => {
@@ -324,18 +333,21 @@ const TextInput: React.AbstractComponent<
324333
}
325334

326335
function handleSelectionChange(e) {
327-
if (onSelectionChange) {
328-
try {
329-
const node = e.target;
330-
const { selectionStart, selectionEnd } = node;
331-
e.nativeEvent.selection = {
332-
start: selectionStart,
333-
end: selectionEnd
334-
};
336+
try {
337+
const { selectionStart, selectionEnd } = e.target;
338+
const selection = {
339+
start: selectionStart,
340+
end: selectionEnd
341+
};
342+
if (onSelectionChange) {
343+
e.nativeEvent.selection = selection;
335344
e.nativeEvent.text = e.target.value;
336345
onSelectionChange(e);
337-
} catch (e) {}
338-
}
346+
}
347+
if (prevSecureTextEntry.current === secureTextEntry) {
348+
prevSelection.current = selection;
349+
}
350+
} catch (e) {}
339351
}
340352

341353
useLayoutEffect(() => {

0 commit comments

Comments
 (0)
Please sign in to comment.