Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 237
EFC Avatar asked Jan 17 '19 00:01

EFC


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.

like image 163
Ryan Cogswell Avatar answered Oct 19 '22 07:10

Ryan Cogswell