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:
JavaScript
x
7
1
<textField
2
value={value}
3
fullWidth
4
autoFocus
5
onFocus={event => {
6
event.target.select()}} />
7
but this will select all text inside the textField.
How can I select only a part of the text?
ex: if i have myfile.doc i would be selected only myfile
like this
Thanks
Advertisement
Answer
Use the setSelectionRange in combination with the lastIndexOf
method to find the position of the last .
.
JavaScript
1
20
20
1
class App extends React.Component {
2
handleFocus = event => {
3
event.preventDefault();
4
const { target } = event;
5
const extensionStarts = target.value.lastIndexOf('.');
6
target.focus();
7
target.setSelectionRange(0, extensionStarts);
8
}
9
10
render(){
11
return (
12
<input
13
value={'myfile.doc'}
14
onFocus={this.handleFocus}
15
/>
16
)
17
}
18
}
19
20
ReactDOM.render(<App />, document.getElementById('root'));
JavaScript
1
3
1
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
2
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
3
<div id="root"></div>