Is there a way to programmatically highlight/select text that is inside a TextInput component?
Is there a way to programmatically highlight/select text that is inside a TextInput component? Show activity on this post. You can use selectTextOnFocus to achieve this. This will ensure that all text inside the TextInput is highlighted when the field is tapped into. Show activity on this post.
The TextInput class supports the editing of text. It displays a background skin and uses a text editor to allow the user to modify the text. First, let's create a TextInput control and add it to the display list:
It can perform validation of required field, minimum or maximum length, email and URL formats, regular expression patterns, and custom rules. Text Input can display a character count, automatically capitalize or check spelling, and supports autofill types. The following examples demonstrate some of the available functionality for Text Input.
For creating a TextInput in react native we have to import the TextInput component from React Native. allowFontScaling: This property will specify if the fonts will scale to respect Text Size accessibility settings. The default value for this is true.
You can use selectTextOnFocus
to achieve this. This will ensure that all text inside the TextInput
is highlighted when the field is tapped into.
Actually you can, by accessing textInput's method by refs.
<TextInput ref={input => this.myInput = input} selectTextOnFocus style={{height: 100, width: 100}} defaultValue='Hey there' />
and where you want to select all text programmatically you can
this.myInput.focus()
works on iOS, not sure about android.
Reference : http://facebook.github.io/react-native/releases/0.45/docs/textinput.html#selectionstate
I don't know if there's a better way, but I found a workaround. The text has to be focused first. Here's an example
import React { Component } from 'react';
import { Button, TextInput, findNodeHandle } from 'react-native';
import TextInputState from 'react-native/lib/TextInputState';
class MyComponent extends Component {
render() {
return (
<View style={{ flex: 1, }}>
<Button
title="select text"
onPress={() => {
TextInputState.focusTextInput(findNodeHandle(this.inputRef))
}}
</
<TextInput
selectTextOnFocus
ref={ref => this.inputRef = ref}
/>
</View>
);
}
}
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