Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Material UI Text Field, Current Cursor Position

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.

like image 313
Nicholas Hamilton Avatar asked Oct 17 '19 04:10

Nicholas Hamilton


1 Answers

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);

Edit TextField selectionStart

like image 182
Ryan Cogswell Avatar answered Nov 09 '22 21:11

Ryan Cogswell