react-native
react-native copied to clipboard
Nested Text with onPress / TouchableOpacity Bug
Hey there. I found an issue when rendering nested Text elements. It's almost the exact same as this ticket: https://github.com/facebook/react-native/issues/1030
I was able to get it to sort of work. I had to add an onPress to the Text component.
Problems:
- TypeScript says there isn't an
onPresson Text elements. But it does in fact work. This should probably be fixed in the type definitons. - Not possible to use TouchableOpacity, so it doesn't feel good when pressing on these items.
When using TouchableOpacity like this:
<Text>
<Text>first part</Text>
<TouchableOpacity><Text>Second part</Text></TouchableOpacity>
</Text>
Second part doesn't get rendered at all.
Before you suggest using a <View> around the <Text> instead, please look at the referenced issue. When you do that, the text runs off screen, or wraps weirdly.
TLDR; I need to add a touchable opacity inside a nested Text component. Our api returns text in blocks, the RN app needs to parse it and render an array of text elements together with different styling.
React Native version:
0.61.4
Hey there, it looks like there has been no activity on this issue recently. Has the issue been fixed, or does it still require the community's attention? This issue may be closed if no further activity occurs. You may also label this issue as a "Discussion" or add it to the "Backlog" and I will leave it open. Thank you for your contributions.
Still a problem
Yeah, it'd be great if this was possible as I just came across the same issue when trying to nest links inside a string of translated text.
Right now, I'm having to use onPress on my Text component and by using that instead of TouchableOpacity, I get no control over hitSlop, activeOpacity, etc. It just gives me an ugly grey background to the text when I press it, which I can only turn off with suppressHighlighting.
Same issue here. I have the following setup:
<TouchableOpacity onLongPress={() => console.log('1')}>
<Text>
<Text>Some text </Text>
<Text onPress={() => console.log('2')}>clickable text</Text>
<Text> another text</Text>
</Text>
</TouchableOpacity>
I understand that we need to use onPress in the nested Text, my example works on Android (both 1 and 2 can be logged). But it seems that on iOS TouchableOpacity hijacks all touch events and doesn't propagate events down to onPress of the Text element. Any chance we can fix it or there are workarounds? Simply using View with flexDirection: row doesn't wrap text intelligently.
FYI: when nesting just Text tags on iOS the gestures get propagated :) So this works:
<Text onLongPress={() => console.log('1')}>
<Text>
<Text>Some text </Text>
<Text onPress={() => console.log('2')}>clickable text</Text>
<Text> another text</Text>
</Text>
</Text>
Any activity on it? 🤔
Hey @zackify, this should help you out :)
<View style={{ flexDirection: 'row' }}>
<Text>first part </Text> // notice the empty space space after part
<TouchableOpacity>
<Text>second part</Text>
</TouchableOpacity>
</View>
@vinaysharma14 looks like the wrapping is broken when you do it like this :(
Hey there, it looks like there has been no activity on this issue recently. Has the issue been fixed, or does it still require the community's attention? This issue may be closed if no further activity occurs. You may also label this issue as a "Discussion" or add it to the "Backlog" and I will leave it open. Thank you for your contributions.
Not fixed yet!
Great we can't do it yet :)
@vinaysharma14 looks like the wrapping is broken when you do it like this :(
Hi @zackify @backmeupplz @Stevemoretz I guess this should work fine :)
<Text>
<Text>
I believe @backmeupplz had said that sentence wrapping would break{' '}
</Text>
<TouchableOpacity>
<Text>here</Text>
</TouchableOpacity>
<Text>
{' '}but it didn’t it!
</Text>
</Text>
@vinaysharma14 does this work on iOS though?
<TouchableOpacity onLongPress={() => console.log('1')}>
<Text>
<Text>Some text </Text>
<Text onPress={() => console.log('2')}>clickable text</Text>
<Text> another text</Text>
</Text>
</TouchableOpacity>
@backmeupplz I didn’t try but it's not OP's requirement.
@vinaysharma14 sure, I can create a separate issue for this
@backmeupplz may I know what functionality are you trying to achieve with this code snippet? I'm unable to understand the usecase of adding touchable on entire text and an onPress on a word.
@vinaysharma14 sure. It's a text of a todo in a list of todos. Todo text has links in it. Tapping the text in general copies the whole text. Taping the links opens links.
@backmeupplz I visualised the code you wrote into a wireframe. Can you confirm if this is the desired behaviour?
@vinaysharma14 this looks correct, yes. I can't remember if I had a long tap on the outer side or just a single tap, it was a while ago — but general idea is correct
@backmeupplz thanks for confirming that. Either it's a long or single tap, TouchableOpacity is sufficient. So, if we are able to get it working, both taps would work. If you are seeking a solution to this, you can give a thumbs up and I can check if we can implement it in React Native.
Hi @backmeupplz, you may check the implementation below.
GIF Demo

Code
import React, { useCallback, Children } from 'react';
import {
View,
Linking,
TextInput,
StyleSheet,
SafeAreaView,
Text as RNText,
TouchableOpacity,
} from 'react-native';
import RNClipboard from '@react-native-clipboard/clipboard';
// =================== Reusable Components =================== //
const Text = ({ children, style = {} }) => (
<RNText style={[styles.text, style]}>{children}</RNText>
);
const Link = ({ text, link }) => {
const openLink = useCallback(() => {
Linking.openURL(link);
}, [link]);
return (
<TouchableOpacity style={styles.touchable} onPress={openLink}>
<Text style={styles.red}>{text}</Text>
</TouchableOpacity>
);
};
const Clipboard = ({ text, children }) => {
const copyToClipboard = useCallback(() => {
RNClipboard.setString(text);
}, [text]);
return (
<TouchableOpacity onPress={copyToClipboard}>{children}</TouchableOpacity>
);
};
// ===================== Util Function ===================== //
const isString = value => typeof value === 'string';
// ===================== Mock Links ===================== //
const { name, rapidReact, mmt, react, reactNative, node } = {
name: {
text: 'Vinay Sharma',
link: 'https://www.linkedin.com/in/vinaysharma-/',
},
rapidReact: {
text: 'Rapid React',
link: 'https://www.npmjs.com/package/rapid-react',
},
mmt: {
text: 'MakeMyTrip',
link: 'https://www.makemytrip.com/',
},
react: {
text: 'React',
link: 'https://reactjs.org/',
},
reactNative: {
text: 'React Native',
link: 'https://reactnative.dev/',
},
node: {
text: 'Node',
link: 'https://nodejs.org/en/',
},
};
// ================== Mock Message ================== //
const mockMsg = [
'Hi, my name is ',
name,
'. I am the author of ',
rapidReact,
' and a SDE at ',
mmt,
'.\n\n',
'I love developing Full Stack applications with ',
react,
', ',
reactNative,
', ',
node,
' and much more!',
];
const stringifiedMockMsg = mockMsg
.map(msg => (isString(msg) ? msg : msg.text))
.join('');
// ===================== App ===================== //
const App = () => {
return (
<SafeAreaView style={styles.container}>
<View style={styles.subContainer}>
<Clipboard text={stringifiedMockMsg}>
<Text>
{Children.toArray(
mockMsg.map(msg =>
isString(msg) ? <Text>{msg}</Text> : <Link {...msg} />,
),
)}
</Text>
</Clipboard>
</View>
<TextInput
multiline
placeholder="Paste here"
placeholderTextColor="#999"
style={[styles.subContainer, styles.input]}
/>
</SafeAreaView>
);
};
// ===================== Styles ===================== //
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
backgroundColor: '#fff',
},
subContainer: {
padding: 20,
borderWidth: 1,
borderRadius: 5,
borderColor: '#000',
marginHorizontal: 50,
},
input: {
height: 180,
marginTop: 50,
paddingTop: 20,
},
touchable: {
marginBottom: -3,
},
text: {
fontSize: 15,
},
red: {
color: 'red',
},
});
export default App;
Package.json
{
"name": "foo",
"version": "0.0.1",
"private": true,
"scripts": {
"android": "react-native run-android",
"ios": "react-native run-ios",
"start": "react-native start",
"test": "jest",
"lint": "eslint ."
},
"dependencies": {
"@react-native-clipboard/clipboard": "^1.8.1",
"@react-native-community/clipboard": "^1.5.1",
"react": "17.0.1",
"react-native": "0.64.2"
},
"devDependencies": {
"@babel/core": "^7.12.9",
"@babel/runtime": "^7.12.5",
"@react-native-community/eslint-config": "^2.0.0",
"@types/react-native": "^0.64.10",
"babel-jest": "^26.6.3",
"eslint": "7.14.0",
"jest": "^26.6.3",
"metro-react-native-babel-preset": "^0.64.0",
"react-test-renderer": "17.0.1"
},
"jest": {
"preset": "react-native"
}
}
@vinaysharma14 thank you for such a thorough investigation and for the example! It looks like this works :) Cheers!
Recently I encountered the same issue, as I had to render urls differently than a simple text in chat. I tried 3 different Approach, out of which the last approach worked pretty neatly and does what I want.
What I want:
- It should render url and plain text differently
- It should have access to all touch events same as any Touchable components, i.e onPressIn, onLongPress, onPressOut, and onPress
- It should be able to wrap multiline messages
const MessageBox = (message) => {
const URL_REGEX =
/https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)/;
return (
<Text>
{message.split(" ").map((word) =>
URL_REGEX.test(part) ? (
<Text
onResponderGrant={(event) =>
console.log(
"this is the time to highlight and show the user what is happening"
)
}
onLongPress={() => console.log("use this to copy message")}
onResponderRelease={(event) =>
console.log("this is the time to open link in the browser")
}
>
{url}
</Text>
) : (
<Text>{word}</Text>
)
)}
</Text>
);
};
@devendra-learngram-ai is there any example of how to use the onResponderGrand and onResponderRelease to imitate touchableopacity animation on text onPress?
It's 2022 and we still can't make a proper clickable text that's inside a paragraph.
<Text
style={{
marginTop: 45,
width: 167,
textAlign: 'center'
}}
>
Don’t have an account yet?{' '}
<TouchableOpacity
onPress={() => {
console.log('fuck');
}}
>
<Text style={{ color: 'red' }}>Create account</Text>
</TouchableOpacity>{' '}
now!
</Text>
The code above, you be able to render a paragraph, but the touchable text is not properly aligned. It will be pushed up by a few pixels and I can't find a workaround to fix it.
We have self driving cars but can't do a proper touchable text, ironic.
Don't use touchable opacity use a Text also it has an onPress prop, you can also modify the style for that.
Don't use touchable opacity use a Text also it has an onPress prop, you can also modify the style for that.
I know, but that won't have a proper response, I tried making my own with Animated.Text but the opacity won't work unless I wrap it inside View but that produces the same problem -- the text will be misaligned.
@devendra-learngram-ai is there any example of how to use the onResponderGrand and onResponderRelease to imitate touchableopacity animation on text onPress?
You could try with reanimated2 Animated.Text that might actually work without any problems. Haven't tested it myself yet though it should be pretty easy to test.
Don't use touchable opacity use a Text also it has an onPress prop, you can also modify the style for that.
I know, but that won't have a proper response, I tried making my own with
Animated.Textbut the opacity won't work unless I wrap it inside View but that produces the same problem -- the text will be misaligned.
Yeah I meant only it works without the animation, but if you need animation let me try with reanimated 2 and report the results here.
I'm using "react-native-reanimated": "^2.4.1" it didn't work, the opacity won't work until you wrap the Animated.Text inside the View. I deleted the whole code for it out of frustration, because I've been stuck here for about 1.5h searching on google for answers, I tried adding marginTop: -3 and it worked for ios (the text was aligned) but not for android. I'll just stick to unresponsive touchable text I suppose. It's a shame but it is what it is.