react native touchable highlight and touchable native feedback for making my menu items

Like you said, TouchableNativeFeedback is Android only therefore it won't work for iOS. If you want a solution that works for both, use TouchableHighlight and style it accordingly. For example, its underlayColor prop allows you to set "the color of the underlay that will show through when the touch is active."

EDIT:

If you want to use TouchableNativeFeedback for Android and TouchableHighlight for iOS, you should do something like the following:

import { Platform } from 'react-native'
...

render() {
    if (Platform.OS === 'android') {
       return (
          <TouchableNativeFeedback> 
               ... 
          </TouchableNativeFeedback>    
       )
    } else {
       return (
          <TouchableHighlight> 
               ... 
          </TouchableHighlight>    
       )
    }
}

EDIT 2:

Alternatively, you can create a custom component for each platform and use file extensions. For example:

MyButton.ios.js
MyButton.android.js

Put these two in the same folder and then use MyButton as a regular component:

import MyButton from '../path/to/component/MyButton'
...

render() {
   <MyButton/>
}

This is quite neat when you want to use this component in multiple places because you don't fill your code with if-else blocks.

Here you can read more about Platform Specific Code.


You can solve this in a more elegant manner like this:

render() {
    let TouchablePlatformSpecific = Platform.OS === 'ios' ? 
        TouchableOpacity : 
        TouchableNativeFeedback;

    let touchableStyle = Platform.OS === 'ios' ? 
        styles.iosTouchable : 
        styles.androidTouchable

    return(
        <TouchablePlatformSpecific style={touchableStyle}>
            (...)
        </TouchablePlatformSpecific>   
    );
}    

I've been using this successfully, and I fail to see a reason it would not work, it looks good to me.


A better implementation would be to have dumb component that produces generic Touchable that works depending upon the platform and handle onPress events.

Touchable Component:

import { Platform } from "react-native"


import { TouchableNativeFeedback, TouchableOpacity } from "react-native"
import React from "react"

export const Touchable = (props: any) => {
  return Platform.OS === 'android'
    ? <TouchableNativeFeedback onPress={props.onPress}>{props.children}</TouchableNativeFeedback>
    : <TouchableOpacity onPress={props.onPress}>{props.children}</TouchableOpacity>
}

Usage:

import { Touchable } from '../path/to/touchable.component';
...
render() {
    <Touchable onPress={() => this.handleClick()}>
         .....
    </Touchable>
}

Thanks to @Giorgos' implementation which formed the basis for this answer.

Tags:

React Native