How to convert string to lowercase? .toLowerCase() not working properly

Viewed 311

I want to make an input field that returns imputed text in lower case. I'm using expo

const [login, setLogin] = useState('');
//...
<TextInput style={{backgroundColor:'#bbb'}}
   value={login}
   onChangeText={(val)=>setLogin(val.toLowerCase())}
   placeholder="email or username"
></TextInput>

I'm getting a strange result when testing it on my device.

my input: 'K' => login = 'k'

my input: 'k' => login = 'kkk'

my input: 'k' => login = 'kkkkkkk'

You may need to try a few times to recreate my result as it doesn't happen every time. When I remove .toLowerCase(), it works correctly.

I made runnable example for you to test. Running it in web mode works fine, but when I run it on my device, the same error is occurring as in my project.

Here is a video of what's happening to me when I run it on android 10. You can see that it doesn't happen always, but sometimes it registers as if I've pressed "q" three times when I've only pressed it twice

1 Answers

I think you run into a known react-native bug, related to text inputs and capitalization on Android platform. Open github issue #27449.

As a workaround you can force the text input to use the visible-password keyboard type on Android.

Working example for you to test:

import React, { useState } from 'react';
import { Text, View, StyleSheet, TextInput } from 'react-native';
import { Platform } from 'react-native';

export default function App() {
  const [login, setLogin] = useState('');
  return (
    <View style={styles.container}>
      <TextInput style={{backgroundColor:'#bbb'}}
        value={login}
        onChangeText={(val)=>setLogin(val.toLowerCase())}
        keyboardType={Platform.OS === 'ios' ? 'default' : 'visible-password'}
        placeholder="email or username"
      ></TextInput>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    padding: 80,
  },
});

Credit for the workaround goes to simon-davies-avtura

Related