Sometimes, we want to select part of text in a Textfield on onFocus event with Material UI in React.
In this article, we’ll look at how to select part of text in a Textfield on onFocus event with Material UI in React.
How to select part of text in a Textfield on onFocus event with Material UI in React?
To select part of text in a Textfield on onFocus event with Material UI in React, we can set the onFocus
prop to a function that does the text selection.
For instance, we write:
import React from "react";
import TextField from "@material-ui/core/TextField";
export default function App() {
const handleFocus = (event) => {
event.preventDefault();
const { target } = event;
const extensionStarts = target.value.lastIndexOf(".");
target.focus();
target.setSelectionRange(0, extensionStarts);
};
return (
<div>
<TextField value="myfile.doc" onFocus={handleFocus} />
</div>
);
}
We set the onFocus
prop to handleFocus
.
The function calls preventDefault
to stop the default focus behavior.
Then we call target.focus
to focus on the text input.
Finally, we call setSelectionRange
with the start and end index of the input value to highlight.
The character at the end index is excluded from the selection.
Conclusion
To select part of text in a Textfield on onFocus event with Material UI in React, we can set the onFocus
prop to a function that does the text selection.