Skip to content
Advertisement

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

Advertisement

Answer

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>
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement