How can I get the current cursor (caret) position in a materialUI text field?
https://material-ui.com/components/text-fields/
Basically, I have a need to modify the string contents at a particular index (for example, insert a char X between char #3 and char #4).
I understand that using the onChange
, onClick
and onFocus
events will flag that a position change may have taken taken place (ie click mouse, or, say move using left/right arrow buttons, or type something), but then if I have a reference to the text-field object, which method or property would then permit me to determine where the caret is exactly positioned (index value 0 .. n-1
)?
In jQuery
, I think this can be obtained via the selectionStart
property, so how exactly is the best way for a MaterialUI textfield?
Many thanks.
You can use the inputRef prop to get a ref to the input
DOM element. That ref can then be used to get the selectionStart
property of the DOM element.
Working example:
import React from "react";
import ReactDOM from "react-dom";
import TextField from "@material-ui/core/TextField";
function App() {
const inputRef = React.useRef();
const [selectionStart, setSelectionStart] = React.useState();
const updateSelectionStart = () =>
setSelectionStart(inputRef.current.selectionStart);
return (
<div className="App">
<TextField
onSelect={updateSelectionStart}
inputRef={inputRef}
defaultValue="Initial Text"
/>
<br />
<br />
selectionStart: {selectionStart}
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With