When user types text in TextInput
, onChangeText
and onChange
are called.
I am getting event
from onChange
callback and can get newly updated text from event.nativeEvent.text
.
I am getting text
from onChangeText
callback and can get newly updated text from it.
But I only want newly entered text/letters. How to get this?
For example:-
lets assume we have som
as text in TextInput
, now as soon as user type e
, I want only this e
instead of whole text some
.
Any work around?
We can get newly typed letters via
Use onSelectionChange
props in your Input
. We can get an event
from onSelectionChange
from which we can get cursor
position. Through cursor
position and full text we can easily get newly entered letters.
Example:-
<Input
...
onChangeText={this.handleMessageChange}
onSelectionChange={this.handleMessageSelectionChange}
...
/>
And methods
handleMessageChange = (message: string) => {
this.setState({ message });
};
handleMessageSelectionChange = (event: Object) => {
const { selection } = event.nativeEvent;
this.setState({ selection });
};
Now whenever you want newly entered letters, get it
getNewlyEnteredLetters = (): string => {
const { selection, message } = state;
const { start, end } = selection;
return start === end ? message[start -1 ] : message[message.length - 1]
}; // start === end implies that new letters are entered and not selection is made.