Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native - Setting TextInput cursor position

Tags:

In my React Native app, I am trying to set the cursor position of a TextInput to a particular position (eg. to the 5th character) but am have trouble doing so as the documentation is lacking a little. I suspect it has something to do with the 'setSelection' property of TextInput but I cannot seem to find out what to do.

Has anyone successfully done so?

Thanks.

like image 535
coldbuffet Avatar asked Nov 13 '15 05:11

coldbuffet


People also ask

How do I get cursor position in React Native TextInput?

In order to get the position of the cursor the only thing you need is onSelectionChange https://reactnative.dev/docs/textinput#onselectionchange. The function will return the start and the end values.

How do I change my cursor in React Native?

To change the React Native text input cursor color, we can set the selectionColor prop to the cursor color. to set selectionColor to 'green' to set the cursor color on the text input to green.


1 Answers

As @this.lau_ says there is a controlled property called selection which accepts an object with keys start and end.

Example:

class ControlledSelectionInput extends Component {     state = {         selection: {             start: 0,             end: 0         }     }      // selection is an object: { start:number, end:number }     handleSelectionChange = ({ nativeEvent: { selection } }) => this.setState({ selection })      render() {         const { selection } = this.state;          return <TextInput selection={selection} onSelectionChange={this.handleSelectionChange} />     } } 

You can also programmatically set the selection by getting a ref to the component and using setNativeProps like this:

this.inputRef.setNativeProps({ selection:{ start:1, end:1 } }) 

Example:

class SetNativePropsSelectionInput extends Component {     inputRef = null      render() {         const { selection } = this.state;          return (             <View>                 <TextInput ref={this.refInput} />                 <Button title="Move selection to start" onPress={this.handleMoveSelectionPress} />             </View>     }      refInput = el => this.inputRef = el      handleMoveSelectionPress = () => this.input.setNativeProps({         selection: {             start: 0,             end: 0         }     }) } 
like image 61
Noitidart Avatar answered Sep 24 '22 12:09

Noitidart