androidreact-nativetextinputuse-refreact-native-textinput

useRef() does not work in Android app (react native)


I have several TextInput that I am using on a math app. The user can put a number and at the end click on a button and that textInput shows the right answer. I use useRef to work with this values as I don't want re-renders with UseState. I use expo and testing in a browser , it all works but once I test on android, the only thing that works with useRef is clear.

example

<TextInput
    onChangeText={ActionChange} 
    ref={refTextInput}
    style={styles.somestyles} 
    keyboardType='numeric'  
    placeholder="?"
    ></TextInput>

I use refTextInput.current.clear() that works and then on showing the results I use:

refTextInput.current.style.color='red' - works on browser not in android refTextInput.current.value=ValueOne+ValueTwo - works on browser not in android

onChangeText is also working everywhere without problem.

I am looking how else I can do it or why it does not work. Thank you


Solution

  • You can use setNativeProps

    to read more about it: https://reactnative.dev/docs/0.66/direct-manipulation

    so your code will be something like that:

     function changeColor(e) {
          if(Platform.OS == "android") 
             refTextInput.current.setNativeProps({backgroundColor:"red"}) // android
          else if(Platform.OS == "web")
             e.target.style.backgroundColor="red"// web 
          }
        onChangeText={(e)=>changeColor(e)}