Skip to content

Instantly share code, notes, and snippets.

@ross-u
Created June 10, 2020 12:58
Show Gist options
  • Save ross-u/a2bb53f38efb57a923e82ccc860cc658 to your computer and use it in GitHub Desktop.
Save ross-u/a2bb53f38efb57a923e82ccc860cc658 to your computer and use it in GitHub Desktop.
React - Send cursor to the end of the text/password input
import React, { useState, useEffect, useRef, useCallback } from "react";
function TextField() {
const [type, setType] = useState("text");
const [inputValue, setInputValue] = useState("text");
const inputRef = useRef();
const handleChange = e => setInputValue(e.target.value);
const onToggle = useCallback(() => {
setType(type === "text" ? "password" : "text");
inputRef.current.type = type;
});
useEffect(() => {
// Moving cursor to the end
const strLength = inputRef.current.value.length;
inputRef.current.setSelectionRange(strLength, strLength);
inputRef.current.focus();
}, [type]);
return (
<div>
<input
ref={inputRef}
type={type}
value={inputValue}
onChange={handleChange}
/>
<button onClick={onToggle}>toggle type</button>
</div>
);
}
export default function App() {
return (
<div className="App">
<TextField />
</div>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment