19

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?

Ryan Cogswell
  • 75,046
  • 9
  • 218
  • 198
EFC
  • 1,890
  • 18
  • 39
  • Please include the code that you used in your attempt. – Ryan Cogswell Jan 17 '19 at 00:41
  • 1
    Turns out that this is not a Material-UI issue at all. Thanks, Ryan, for pushing me a bit. Here is another React App without any Material components exhibiting the same behavior on Safari. Interesting to note that when I create a similar static page without any React at all, this static app works just fine, even in Safari. So I think the problem is with React and Safari (and Mobile Safari, unfortunately), not with Material-UI at all. – EFC Jan 17 '19 at 04:51
  • FYI, I just asked this question with better code examples and a ReactJS tag at https://stackoverflow.com/q/54229359/383737. – EFC Jan 17 '19 at 05:08
  • This got a nice answer at https://stackoverflow.com/a/54229871/383737. – EFC Jan 18 '19 at 06:17

1 Answers1

28

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.

Ryan Cogswell
  • 75,046
  • 9
  • 218
  • 198
  • 2
    Thank you for this example, oddly enough it behaved just the same as my own (very similar) code. Then I thought to test on another browser. This code works as you would expect on Chrome but does not work properly on Safari (both up-to-date on macOS). I will have to test this in plain Javascript to see if the problem is deeper. – EFC Jan 17 '19 at 04:09
  • I had only tried it on Chrome. I’ll look into this more tomorrow on other browsers if I have time. – Ryan Cogswell Jan 17 '19 at 04:17