Search code examples
reactjsreact-nativereact-native-textinput

Manipulation TextInput selection


I'm trying to make a TextInput with a non-standard placeholder, because I need formatting and the normal, built-in TextInput placeholder doesn't work for me.

In order for the user to start writing from the beginning of the line, as with the normal placeholder, I set the cursor at the beginning of selection={TEXT ? null: {start: 0}. When the user types further, the cursor goes back to the beginning and forces the user to write elloH instead of Hello.

I made an example of my code on Snack, the problem will be clearer when running: https://snack.expo.dev/Vv6lNzUCU

How can this be fixed?


Solution

  • I used Samuli Hakoniemi's idea of opacity and zIndex, but I think I simplified the code a bit:

    import React from 'react';
    import { 
      StyleSheet, 
      View, 
      TextInput, 
      Text
    } from 'react-native';
    
    export default function App() {
      const [TEXT, setText] = React.useState(null);
    
      return (
        <View style={{ marginTop: 100, padding: 20 }}>
          <View>
            <TextInput
              style={{ 
                padding: 5,
                borderWidth: 1,
                zIndex: 1,
              }}
              autoFocus={true}
              onChangeText={(text) => {
                setText(text);
              }}
              value={TEXT}
            />
    
            <View style={{
              position: 'absolute',
              justifyContent: 'center',
              left: 5,
              height: '100%',
              zIndex: 0,
              opacity: (TEXT) ? 0 : 1,
            }}>
              <Text>
                <Text>My </Text>
                <Text style={{ backgroundColor: 'yellow' }}>Example</Text>
              </Text>
            </View>
          </View>
        </View>
      );
    }
    

    Example in Snack: https://snack.expo.dev/mOuNbvxCU