Walter Monecke
Walter Monecke

Reputation: 2558

Dynamic tag name with JSX and React Native

This question is inspired by this question: Dynamic tag name in jsx and React but this time it is for React Native.

I am trying to render a <TouchableOpacity> button for iOS and <TouchableNativeFeedback> button for Android, with no success.

I tried the following code:

render() {
    const { element } = this.props;

    const ButtonElementName = Platform.OS === 'ios' ? 'TouchableOpacity' : 'TouchableNativeFeedback';

    return (
      <ButtonElementName style={styles.sectionEntryContainer}>
        <View style={styles.sectionDayContainer}>  
          <LinearGradient
            style={styles.gradientStyle}
            start={{x: 0, y: 0}} end={{x: 1, y: 0}}
            colors={COLOR_MAP[element.item.data.mood].colors}
          >
            <Text style={styles.sectionDayText}>{ moment(element.item.day, 'D').format('Do') }</Text>
          </LinearGradient>
        </View>
        <View style={styles.sectionDayDescriptionContainer}>
          <Text style={styles.sectionDayText}>{ element.item.data.optionalDescription }</Text>
        </View>
      </ButtonElementName>
    );
  }

but get the following error when trying it on the iOS Simulator:

Invariant Violation: View config not found for name TouchableOpacity

How would I go about doing this without creating a HOC?

Upvotes: 0

Views: 1116

Answers (1)

dentemm
dentemm

Reputation: 6379

You shouldn't reference the element by it's name, but directly by class

import {
  TouchableNativeFeedback,
  TouchableOpacity
} from 'react-native';

const Element = Platform.OS === 'ios' ? TouchableOpacity : TouchableNativeFeedback;

class SomeComponent extends React.Component {

  render() {
    const { element } = this.props;

    return (
      <Element style={styles.sectionEntryContainer}>
        <View style={styles.sectionDayContainer}>  
          <LinearGradient
            style={styles.gradientStyle}
            start={{x: 0, y: 0}} end={{x: 1, y: 0}}
            colors={COLOR_MAP[element.item.data.mood].colors}
          >
            <Text style={styles.sectionDayText}>{ moment(element.item.day, 'D').format('Do') }</Text>
          </LinearGradient>
        </View>
        <View style={styles.sectionDayDescriptionContainer}>
          <Text style={styles.sectionDayText}>{ element.item.data.optionalDescription }</Text>
        </View>
      </Element>
    );
  }
}

Upvotes: 2

Related Questions