25

I am trying to perform something like the following, which React Native does not like.

I want to wrap clickable text in a TouchableOpacity, and with its own styles.

By wrapping it in a parent Text component, all of the text sits perfectly side by side. However, I can't put a TouchableOpacity inside of a Text component.

<View>
  <Text>
    <Text>Hello my name is</Text>
    <TouchableOpacity onPress={this.openProfile}>
      <Text style={styles.clickable}>{ name }</Text>
    </TouchableOpacity>
    <Text>, I am currently working at </Text>
    <TouchableOpacity onPress={this.openCompanyPage}>
      <Text style={styles.clickable}>{ company }</Text>
    </TouchableOpacity>
  </Text>
</View>

I get the error: Views nested within a <Text> must have a width and height. I am unable to set those measurements as I want them to be dynamic and be dependant on the content.

For example name could be John Smith or Hubert Blaine Wolfe­schlegel­stein­hausen­berger­dorff Sr.

As per comment, I want to render portions of the text with custom styles. I can do that effortlessly by placing Text within Text. Now I want to add a clickable area to those portions of text ("Dan", "Google"). But I cannot embed a TouchableOpacity inside of a Text element.

enter image description here

Dan
  • 779
  • 2
  • 8
  • 16

2 Answers2

27

Actually the solution of Bilal Hussain did not work for me. I got an error saying Nesting of <View> within <Text> is not supported on Android.

What worked for me was the solution described in this SO answer. Just using <Text> elements only and applying a onPress property to them like so:

<Text>
        Hello my name is
        <Text style={{color: 'red'}} onPress={function1}>Dan, </Text>
        I am currently working at
        <Text style={{color: 'red'}} onPress={function2}>Google</Text>
</Text>
David Schumann
  • 13,380
  • 9
  • 75
  • 96
18

Dan. You need to achieve this by wrapping everything inside <View> tag and add style accordingly.

try this:

<View style={{flexDirection: 'row', justifyContent: 'center', alignItems: 'center' }}>
        <Text>Hello my name is </Text>
        <TouchableOpacity>
          <Text style={{color: 'red'}}>Dan, </Text>
        </TouchableOpacity>
        <Text>I am currently working at </Text>
        <TouchableOpacity>
          <Text style={{color: 'red'}}>Google</Text>
        </TouchableOpacity>
      </View>

Let me know. Thanks

Ref for more style : https://facebook.github.io/react-native/docs/style.html

Bilal Hussain
  • 994
  • 1
  • 10
  • 25