Reputation: 2193
Is there a way to programmatically highlight/select text that is inside a TextInput component?
Upvotes: 20
Views: 21080
Reputation: 1079
Note: For those who wants to use selectTextOnFocus
short answer. Actually, it works fine in IOS, but doesn't work in Android.
Thanks to Arnav Yagnik; Following is a similar approach in a functional component:
const inputRef = React.useRef(null);
React.useEffect(() => {
if (inputRef.current) {
console.log('focusing !');
inputRef.current.focus();
}
}, []);
return <TextInput
multiline
label="Amount"
selectTextOnFocus
placeholder="Write Count"
value={stockCount.toString()}
/>
Upvotes: 0
Reputation: 1423
I'm here to share my findings. In a List, you might encounter that selectTextOnFocus
is broken. In this case you can use this method selection
. From React-Native I found this:
In my case I had trouble with the selectTextOnFocus
prop in a list. So I had to add a debounce
function to work with selection
prop.
const [shouldSelect, setShouldSelect] = useState(undefined);
const onFocus = () =>{
setShouldSelect({start:0, end:String(text).length});
}
const focus = useCallback(_.debounce(onFocus,500),[shouldSelect]);
<TextInput
selection={shouldSelect}
onBlur={()=>setShouldSelect(undefined)}
onFocus={()=>focus()}// this is important
selectTextOnFocus
ref={r=>onRef(r)}
keyboardType={'number-pad'}
autoCorrect={false}
blurOnSubmit={false}
returnKeyType={'done'}
underlineColorIos={'transparent'}
underlineColorAndroid={'white'}
allowFontScaling={false}
value={String(text)}
/>
Upvotes: 2
Reputation: 19
this.inputRef.focus()
sets focus to the TextInput
component, and then the flag you set in the attributes selectTextOnFocus
does the rest.
Upvotes: 0
Reputation: 792
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
Upvotes: 21
Reputation: 2193
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>
);
}
}
Upvotes: 2
Reputation: 4435
You can use selectTextOnFocus
to achieve this. This will ensure that all text inside the TextInput
is highlighted when the field is tapped into.
Upvotes: 43