Force TextField to select full text on focus

Viewed 3694

I'd like to get a TextField to select the whole text currently in the field whenever I click/tap/focus on the field. I've done this myself in other React apps with an onFocus handler that does an event.target.select(), but this approach does not seem to work with Material-UI. With Material-UI TextFields I can see the selection briefly cover the full text, then it returns to just a cursor blinking at the end of the text.

Any idea how to make this work?

1 Answers

This works fine for me using the following code:

import React from "react";
import ReactDOM from "react-dom";
import TextField from "@material-ui/core/TextField";

function App() {
  return (
    <TextField
      defaultValue="test"
      onFocus={event => {
        event.target.select();
      }}
    />
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Edit rj48vp8rlm

If this does not help with your problem, please share the code that reproduces your issue.

Related