Search code examples
react-nativereact-hooksreact-native-flatlisttouchableopacity

Touchable Opacity in FlatList doesn't respond to touch


I am displaying the state array below using the FlatList provided. However, the TouchableOpacity elements in Key exhibit no response whatsoever to a press. The issue persists even if I change the TO to a button or a pressable. Does anyone have a solution for this issue because it has never happened before even when using very similar code.

const [keyboard, setKeyboard] = useState([
        {char: 'a', background: 'white', border: 'black', text: 'black'},
                                   .
                                   .
                                   .
        {char: 'z', background: 'white', border: 'black', text: 'black'},
    ]);

const Key = ({letter, background, border, textColor}) => {
        return(
            <TouchableOpacity style = {[styles.key, {backgroundColor: {background}}, {borderColor: {border}}]} onPress = {() => console.log({letter})}>
                <Text style = {[styles.letter, {color: {textColor}}]}>{letter}</Text>
            </TouchableOpacity>
        );
    };

<FlatList 
            contentContainerStyle = {styles.keyboard}
            data={keyboard}
            renderItem= {({item}) => <Key letter={item.char} background={item.background} border={item.border} textColor={item.text}/>}
            keyExtractor={(item) => item.char}
            numColumns = {6}
        />

Styles:

keyboard:{
    width: '100%',
    height: '40%',
    alignItems: 'center',
    justifyContent: 'center',
    position: 'absolute',
    transform:[{translateY: 420}],
    flex: 1,
 },
 letter:{
    fontSize: 25,
    fontWeight: 'bold',
    position: 'absolute',

 },
 key:{
    height: 50,
    width: 60,
    borderWidth: 3,
    borderRadius: 10,
    alignItems: 'center',
    justifyContent: 'center',

 },

Solution

  • The issue with this code is that I had a Modal open. TouchableOpacity components seem to not respond to touch when a Modal is open. Instead use a conditionally rendered view.

    {  {CONDITION HERE} ?(
           {WHAT WILL BE RENDERED IF CONDITION IS SATISFIED HERE}
    ):  {WHAT WILL BE RENDERED IF CONDITION IS NOT SATISFIED HERE; null or some other component}}