EFC
EFC

Reputation: 1949

Force TextField to select full text on focus

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?

Upvotes: 24

Views: 11186

Answers (1)

Ryan Cogswell
Ryan Cogswell

Reputation: 81036

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.

Upvotes: 36

Related Questions