Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How select part of text in a Textfield on onFocus event with material-UI in React?

I have a modal form with material -UI TextField in react app, I have a default value, es. a file, and i would select only the name of the file no the extension when the element is load....

I did this code inside the tag TextField:

<textField 
    value={value}
    fullWidth
    autoFocus
    onFocus={event => {
    event.target.select()}} />

but this will select all text inside the textField. enter image description here How can I select only a part of the text? ex: if i have myfile.doc i would be selected only myfile like this enter image description here

Thanks

like image 204
Angelotti Avatar asked Jan 29 '19 08:01

Angelotti


People also ask

How do I get the value of a TextField in React material UI?

First we create a state to store the text input called textInput and assign it the value ''. Then we return a material UI <TextField /> component whose value attribute is set to the textInput state. Doing this we display the current value of the textInput in the <TextField /> .

How do I change the value of TextField material UI?

To set a value for TextField from Material UI with React, we set the value prop of the TextField to a state value. And we set the onChange prop to a function that sets the state to a the value that's inputted. We call the useState hook to create the value state and the setValue function to set the value state's value.

How do I change the color of text in material UI TextField?

To change the text field font color in React Material UI, we call the makeStyles function with an object with the styles we want to apply. to call makeStyles with an object that has the input property that's set to an object with the color property set to 'blue' . Next, we call useStyles to return the classes object.


1 Answers

Use the setSelectionRange in combination with the lastIndexOf method to find the position of the last ..

class App extends React.Component {
  handleFocus = event => {
    event.preventDefault();
    const { target } = event;
    const extensionStarts = target.value.lastIndexOf('.');
    target.focus();
    target.setSelectionRange(0, extensionStarts);
  }
  
  render(){
    return (
      <input
        value={'myfile.doc'}
        onFocus={this.handleFocus}
      />
    )
  }
}

ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
like image 91
gazdagergo Avatar answered Oct 13 '22 03:10

gazdagergo