Amine
Amine

Reputation: 2434

How to change TextInput cursor position in React Native?

I am trying to achieve this behaviour in React Native: The user type for example 5 then ".000" will be added automatically to the TextInput , but the user can add an other number for example 7, the final result should look like "57.000".

I tried to find a workaround but calculating the length of value and add chars accordingly but it didn't work as expected.

Then I found the selection props of the TextInput.

Here is my take on this:

I added this to state

selection: {
  start: 0,
  end: 0
}

Here is my TextInput

<TextInput
        onFocus={setSelection}
        selection={selection}
        keyboardType="numeric"
        onChangeText={(text) => onChangeText("val", text)}
        value={val}
        editable={true}
        selectTextOnFocus={false}
 />

Here is onChangeText method

onChangeText = async (key, value) => {
  var numDots = value;
  if (value.indexOf(".000") === -1) {
    numDots = value + ".000"
  }
  this.setState({ [key]: numDots });
};

And here is the setSelection method

setSelection = () => {
   this.setState({ select: { start: 1, end: 1 } });
};

The problem is whenever I type, the cursor is always focusing on index 0, I think setSelection is not being triggered.

Is there something I'm doing wrong?

I hope someone would help me in this. Thanx in advance.

Upvotes: 1

Views: 5111

Answers (2)

Dishant Chanchad
Dishant Chanchad

Reputation: 787

You can do the following things to make it work

class YourComponent extends React.Component{
      constructor(props) {
       super(props);
       this.state = {
       text:'Hello World',
       selection: {
        start: 0,
        end: 0
       }
  };

this.inputRefs = {};
}

   setSelection = () => {
      this.setState({ select: { start: 1, end: 1 } });
      };

    changeText = (val) => {
     this.inputRefs.input.focus();
    }

    render(){
       return(
          <TextInput 
            onFocus={this.setSelection}
            selection={this.state.setSelection} 
            onChangeText={val => {this.changeText(val)}} 
            value={this.state.text}
             refName={ref => {
             this.inputRefs.input = ref;
             }}
            />
       )
    }
} 
The idea is whenever your TextInput calls the onChangeText call-back put the focus on your TextInput through refs, as your component is responding to onFocus call back we will set the selection on that call back

Upvotes: 1

Amine
Amine

Reputation: 2434

I ended up changing the onFocus prop by onSelectionChange and it's working now.

Upvotes: 1

Related Questions