0

I'm trying to replicate TouchableOpacity, but in a Text component, since when I use TouchableOpacity the text gets uncentered. How do I make it so when I touch the Text, not yet released it, the styles to change?

Followed this: How can I wrap a TouchableOpacity around Text within Text?

noone
  • 123
  • 1
  • 6

1 Answers1

1

You can use the TouchableOpacity onPressIn/onPressOut props (docs: https://reactnative.dev/docs/touchablewithoutfeedback#onpressin)

If you nest the Touchable inside a Text tag, it will stay inline with the rest of your text.

  <Text>Here is a <TouchableOpacity><Text style={{ color: '#beb' }}>link</Text></TouchableOpacity>. It doesn't disrupt the flow of the text</Text>

You could also use a Pressable, which has the same props, or accepts a callback as a child that provides a pressed argument:

<Pressable>
  {(pressed) => (
    <Text style={pressed ? styles.pressed : styles.unpressed>
    ...

Docs for Pressable are here: https://reactnative.dev/docs/pressable

Abe
  • 4,500
  • 2
  • 11
  • 25
  • Yes, but TouchableOpacity creates its own view and dislodges the text from the main line. Is there a way to make the Text style change while being pressed without any new Views being added – noone May 10 '22 at 14:38
  • If you nest the TouchableOpacity (or Pressable) inside a Text tag, it will stay in the same line as the rest of the text. I'll update with an example. – Abe May 10 '22 at 14:41
  • You can't put text in a TouchableOpacity. If you add a TouchableOpacity you have to add another Text component inside and it dislodges the text – noone May 10 '22 at 14:48
  • I'm not sure what you mean. Check this snack: https://snack.expo.dev/@256hz/text-link – Abe May 10 '22 at 14:53
  • 1
    Quite literally, the samo code, but my Text goes a bit higher than the normal text flow. Don't think that the issue would be from class and functional component. But I am doing the same thing and getting a different result. Also I am using tailwind for styles, but I couldn't imagine that being the problem either. – noone May 10 '22 at 15:10
  • It works with built in components, so I would recommend using those or taking out elements until your problem is fixed. – Abe May 10 '22 at 15:42
  • Well is there a way to create a TouchableOpacity with a text? Like add a pressable prop of sort to it? – noone May 10 '22 at 16:11
  • Text has an onPress prop, but not onPressIn - https://reactnative.dev/docs/text#onpress. It'll be easier if you're not fighting RN and use the builtin components though – Abe May 10 '22 at 16:17
  • https://github.com/facebook/react-native/pull/31288/files/b7c5adf12cd6e4684b3dcdccdd23ac5a8c5ed126#diff-8854d86a25d1052c7f65f4d7235198297464645255149b9700171beb00ca67ec doesn't this conclude that onPressIn and onPressOut are added to Text? – noone May 10 '22 at 17:44
  • Oh yeah, looks like it! As long as your RN version is new enough – Abe May 10 '22 at 18:05