Reputation: 79
I'm trying to alter the value of a TextInput
in React Native, so that no matter what, it always forces them to eventually enter the string 'Black'. When they enter a different character, for example Ble, it would change it to Bla instead.
const [text, setText] = useState('');
var matchesinput = ['B', 'Bl', 'Bla', 'Blac', 'Black'];
var matches = ['b', 'bl', 'bla', 'blac', 'black'];
var newText = '';
return(
<>
<TextInput
style = {{...objstyle, ...color}}
value = {text}
onChangeText={newInput => {
if (matches.indexOf(text.toLowerCase()) > -1) {
setText(newInput);
}
else if (newInput != '' && newInput.length < 6) {
newText = matchesinput[newInput.length - 1];
setText(newText);
}
else {
setText(newInput);
}
}}
/>
</>
);
It seems to work for the first character, but the next incorrect character you enter causes it to glitch and jump to 'Bla', and then straight to 'Black', or sometimes it just continues past 'Black' and then disappears.
Any help would be appreciated!
Upvotes: 0
Views: 82
Reputation: 16354
You don't need any complicated matching. Just take the length of the entered string and set state with the first part of 'Black'
of the same length:
const [text, setText] = useState("");
const handleChange = (newText) => setText("Black".substring(0, newText.length));
return <TextInput value={text} onChangeText={handleChange} />;
Note: If text.length
exceeds the length of 'Black'
it will just result in 'Black'
. So it will not be possible to enter more than 5 letters.
Also see String.prototype.substring()
Upvotes: 1