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. 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
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 /> .
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.
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With