Created
June 10, 2020 12:58
-
-
Save ross-u/a2bb53f38efb57a923e82ccc860cc658 to your computer and use it in GitHub Desktop.
React - Send cursor to the end of the text/password input
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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