-
Notifications
You must be signed in to change notification settings - Fork 24.5k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Nested Text with onPress / TouchableOpacity Bug #27549
Comments
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 |
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 |
FYI: when nesting just <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 :( |
[DSY-851] we have a bug when we try to use this feature within another text tag. The open issue: facebook/react-native#27549
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 :) |
Hi @zackify @backmeupplz @Stevemoretz I guess this should work fine :)
|
@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, |
Hi @backmeupplz, you may check the implementation below. GIF DemoCodeimport 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:
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. |
I know, but that won't have a proper response, I tried making my own with |
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. |
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 |
Thanks for responding btw, I really appreciate it. |
Sure! No problem. We at least need to have two events "on text tap" and "on text release" natively added, that way we can easily fix the issue with reanimated (if the animation also works lol) , right now it's impossible, (unless those events exist already that I'm not aware of) |
@cakasuma I didn't want to go through extra trouble after making the Text click work, so I took another path and highlighted text on click to let user know about the click. So I set the state inside |
just testing: <Text
onResponderGrant={() => {
console.log("s");
}}
>
Hello
</Text> Doesn't work! |
Tried with native animated api by react-native: const fadeAnim = useRef(new Animated.Value(0)).current; // Initial value for opacity: 0
useEffect(() => {
Animated.timing(fadeAnim, {
toValue: 1,
duration: 10000,
easing: Easing.linear,
}).start();
}, [fadeAnim]);
return (
<View style={{marginTop: 200}}>
<Animated.Text>
Hi
<Animated.Text
style={{
opacity: fadeAnim,
}}
>
Hello
</Animated.Text>
</Animated.Text>
</View>
); This also works only on the top level text not the nested, must be related to : It's basically impossible right now to implement even a workaround for the animation part. |
With a small addition to @aprilmintacpineda answer, you'll be able to have an aligned TouchableOpacity aligned with a text
After hours of war, I found a workaround to fix the pixels that RN add to TouchableOpacity element when you wrap it within a Text. The key is to add a View element within your TouchableOpacity and wrap all the element within that View and add marginBottom to negative value to align it with text as shown in the following example: <Text style={styles.modalText}>
You can suggest some questions along with answers by send it to us in
<TouchableOpacity onPress={() => console.log("go to contact")}>
<View
style={{
flexDirection: "row",
alignItems: "center",
marginHorizontal: 6,
marginBottom: -4, // <-- This one will take care of the pixels that RN add to TouchableOpacity when you wrap it within Text
}}
>
<ContactIcon width={12} height={12} fill="#08A3FD" />
<Text
numberOfLines={1}
style={{
fontWeight: "bold",
marginLeft: 4,
fontSize: 14,
color: "#08A3FD",
}}
>
contact
</Text>
</View>
</TouchableOpacity>
section
</Text> good luck <3 |
This issue is stale because it has been open 180 days with no activity. Remove stale label or comment or this will be closed in 7 days. |
Issue still exists |
Anybody figure out a good workaround? |
just import TouchableHighlight from 'react-native' package and not from 'react-native-gesture-handler' |
still bugging in 2023 |
Still an issue if used with in parent Text |
How about using I had similar situation in iOS for making 'KeyboardDismissView' which enables to dismiss keyboard when user touches outer area of Input, but I've solved it by implementing // Use <Pressable/> instead of <Touchable~~~/> Components
export default function KeyboardDismissView(props: KeyboardDismissViewProps) {
const { children, style } = props;
return (
<Pressable onPress={Keyboard.dismiss} accessible={false} style={{ ...style, flexGrow: 1 }}>
{children}
</Pressable>
);
};
export default function InputWithButtonScreen () {
return(
<KeyboardDismissView>
<TextInput/>
<Button onPress={()=>{console.log('1')}}>Hello</Button> // <-- Now Press Event gets in this Button, after using <Pressable/>
</KeyboardDismissView>
);
}; |
Give style property "top" to the touchable text component used inside the normal text component:
|
Hey there. I found an issue when rendering nested Text elements. It's almost the exact same as this ticket: #1030
I was able to get it to sort of work. I had to add an
onPress
to the Text component.Problems:
onPress
on Text elements. But it does in fact work. This should probably be fixed in the type definitons.When using TouchableOpacity like this:
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
The text was updated successfully, but these errors were encountered: