React Native: View onPress does not work - react-native

I'm facing a weird problem. In my react native app, if I set onPress event to View it is not triggered but if I set the same to Text inside View, it fires. What am I missing here?
<View style={{backgroundColor: "red", padding: 20}}>
<Text onPress={()=> {
console.log('works');
}
}>X</Text>
</View>
<View style={{backgroundColor: "red", padding: 20}} onPress={()=> {
console.log('does not work');
}
}>
<Text>X</Text>
</View>
Why is this so? Is this an issue with React Native? I'm using version 0.43

You can use TouchableOpacity for onPress event.
View doesn't provide onPress prop.
<TouchableOpacity style={{backgroundColor: "red", padding: 20}} onPress={()=> {
console.log('does not work');
}
}>
<Text>X</Text>
</TouchableOpacity>

You can wrap the view with a TouchableWithoutFeedback and then use onPress and friends like usual. Also you can still block pointerEvents by setting the attribute on on the child view, it even blocks pointer events on the parent TouchableWithoutFeedback, its interesting, this was my need on Android, I didn't test on iOS:
https://facebook.github.io/react-native/docs/touchablewithoutfeedback.html
<TouchableWithoutFeedback onPressIn={this.closeDrawer}>
<Animated.View style={[styles.drawerBackground, styleBackground]} pointerEvents={isOpen ? undefined : 'none'} />
</TouchableWithoutFeedback>

Alternatively you can also provide onStartShouldSetResponder to your view, like so:
<View onStartShouldSetResponder={() => console.log("View click")}>
// some code here
</View>

You can use TouchableOpacity, TouchableHighlight, TouchableNativeFeedback, to achieve this. View component doesn't provide onPress as props. So you use these instead of that.
<TouchableNativeFeedback
onPress={this._onPressButton}
</TouchableNativeFeedback>
OR
<TouchableHighlight onPress={this._onPressButton}>
</TouchableHighlight>
OR
<TouchableOpacity onPress={this._onPressButton}>
</TouchableOpacity>

onPress doesn't work on <View> tag use <TouchableOpacity> instead of View
<View>
<TouchableOpacity onPress={() => 'call your function here'}>
</TouchableOpacity>
</View>

For this issue you can make use either
touchable(opacity,withoutfeedback,....)
or Pressable component which is currently available in react native Package like,
<TouchableOpacity onPress={()=>console.log("Pressed")}>
....
</TouchableOpacity>
or
<Pressable onPress={()=>console.log("Pressed")}>
....
</Pressable>

2021
If you're looking for a more extensive and future-proof way to handle touch-based input, check out the Pressable API.
Source: https://reactnative.dev/docs/touchablewithoutfeedback

A new pressable component is provided in 0.67 of react native, which can solve your problem. It runs anywhere
enter image description here

well we can make the View have a onPress props onStartShouldSetResponder and onResponderGrant
<View
onStartShouldSetResponder={() => true}
onResponderGrant={() => console.log("view pressed")}
>
</View>

You can use TouchableOpacity for that purpose
<TouchableOpacity onPress={() => {your code here}}>
//Your inner views here
</TouchableOpacity>

In View onPress will not work because onPress event is not supported in view tag.That is why it is not working but you can go to this link https://reactnative.dev/docs/view

You can use Pressable components which is react native core component and wrap your View or any other component in Pressable which don't have onPress prop.
Like this:
<Pressable onPress={()=>console.log('pressed')}>
<View>
<Text>Some Text</Text>
</View>
</Pressable>
Pressable Documentation

For anybody who's lookig for a solution to this, as of RN 0.63, there is a new Pressabe api. It might have rolled out a couple versions earlier but it works great for such use cases.
<Pressable onPress={onPressFunction}>
<Text onPress={() => {
console.log('works');
}}>X</Text>
</Pressable>

Related

Why does TouchableOpacity automatically trigger onPress in ReactNative Expo Snack?

I have a small ReactNative app in Expo Snack that includes a single components with a TouchableOpacity.
export default function AssetExample() {
function clicked() {
alert('clicked')
}
return (
<View style={styles.container}>
<TouchableOpacity onPress={clicked()}>
<Text style={styles.paragraph}>
Click the icon
</Text>
<Image style={styles.logo} source={require('../assets/snack-icon.png')} />
</TouchableOpacity>
</View>
);
}
Every time the app is started the alert is shown, meaning TouchableOpacity triggers onPress. Why? And how can I circumvent this?
You should pass the reference of your function to TouchableOpacity like this
<TouchableOpacity onPress={clicked}>
</TouchableOpacity>
or pass it with arrow function
<TouchableOpacity onPress={()=> clicked()}>
</TouchableOpacity>
so it will be called inside TouchableOpacity component whenever required (button click), otherwise it will be called only one time during render phase.
See these docs for handling events in React https://reactjs.org/docs/handling-events.html

TouchableHighlight not working although using the source code from official react native documentation

I'm a new react native developer and I have an issue with TouchableHighlight where it always shows an error "Error: React.Children.only expected to receive a single React element child." in addition while I remove it is work as usual and I assume if this issue come from my device/vscode/browser. Because I already follow the source code from https://reactnative.dev/docs/touchablehighlight but still show that error.
Error image
Image without TouchableHighlight tag
Here my code
render() {
return (
<View style={styles.container}>
<TouchableHighlight onPress={this.onPress}>
<View style={styles.button}>
<Text>Touch Here</Text>
</View>
</TouchableHighlight>
<View style={[styles.countContainer]}>
<Text style={[styles.countText]}>
{this.state.count ? this.state.count : null}
</Text>
</View>
</View>
);}
From the error message, the issue might happen if you pass Mutlipe child components to TouchableHighlight
From the docs:
TouchableHighlight must have one child (not zero or more than one). If you wish to have several child components, wrap them in a View
<TouchableHighlight onPress={onPress}>
<View style={styles.button}> // Mutlipe child components are wrapped in a View
<Text>Touch</Text> // component 1
<Text>Here</Text> // component 2
</View>
</TouchableHighlight>

Style breaks when using TouchableOpacity instead of TouchableWithoutFeedback

Here's how this part looks using TouchableWithoutFeedback
And here is the same thing, except with TouchableOpacity
The code for this part:
<TouchableWithoutFeedback>
<View style={styles.buyCoinsItem}>
<View style={styles.cost}>
<Text>{no_of_coins}</Text>
</View>
<Text>{product.priceString}</Text>
<View style={{height:30, flexDirection: 'row', marginTop:10}}>
{displayDiscount &&
<View style={styles.discountContainer}>
<Text style={styles.whiteText}>Save {discount}</Text>
</View>
}
</View>
</View>
</TouchableWithoutFeedback>
What's going on here?
This is an annoying side effect of how the two components are implemented.
Essentially, TouchableOpacity is a native-backed View that supports touch interactions by calling setNativeProps({ opacity }) on that view, whereas TouchableWithoutFeedback is simply wraps a native view and attaches the touch handlers.
In order to make TouchableWithoutFeedback behave like TouchableOpacity, nest an additional View inside it, and define any styles on the child view:
Before:
<TouchableOpacity onPress={...} style={styles.touchable}>
// Touchable content
</TouchableOpacity>
After:
<TouchableWithoutFeedback onPress={...}>
<View style={styles.touchable}>
// Touchable content
</View>
</TouchableWithoutFeedback>
I'm not sure why the API was designed this way - my guess would be to avoid creating an additional native backing view for performance reasons when it's not needed.
However, from refactoring purposes, this makes it slightly more painful to move between different types of Touchables. In my projects, I typically create a custom Touchable component that wraps this logic behind a prop, or use something like react-native-platform-touchable, which gives you Android Material-style effects on Android.
Nvm, I figured it out. I basically switched the TouchableOpacity with the outer View. So, like this:
<View style={styles.buyCoinsItem}>
<TouchableOpacity>
<View style={styles.cost}>
<Text>{no_of_coins}</Text>
</View>
<Text>{product.priceString}</Text>
<View style={{height:30, flexDirection: 'row', marginTop:10}}>
{displayDiscount &&
<View style={styles.discountContainer}>
<Text style={styles.whiteText}>Save {discount}</Text>
</View>
}
</View>
</TouchableOpacity>
</View>

React Native detect tap on View

I’m writing a React Native app and I want to detect tap/clicks anywhere on the screen so I put an onClick handler on my <View> element but it doesn’t seem to be working. Here is my render function:
<View style={styles.container} onClick={this.onClick}>
<Text style={styles.welcome}>
Tap to change the background
</Text>
</View>
What do I need to do?
For making any element to handle touch/click events in a React-Native UI, you need to put the element inside a TouchableOpacity, TouchableWithoutFeedback, TouchableNativeFeedback or TouchableHighlight element:
<TouchableHighlight onPress = { this.onClick }>
<View style={styles.container}>
<Text style={styles.welcome}>
Tap to change the background
</Text>
</View>
</TouchableHighlight>
Hope that helps.
In React Native version > 55.3 you make check onPress events into your View if use onStartShouldSetResponder props.
Like example:
<View
style={{ flex: 1 }}
onStartShouldSetResponder={() => console.log('You click by View')}
>
<ScrollView
refreshControl={
<RefreshControl
refreshing={this.state.refreshing}
onRefresh={this.onRefresh} />
}
>
<Text>Awesome</Text>
</ScrollView>
</View>
In example I showed how you can get onPress event on View and not blocking other event behind them. Refresh control still work correct.
In my case the following works fine. You can use onTouchStart and onTouchEnd handlers on any View via props, for example:
<View onTouchStart={() => this.doSomething()} />
More information
This worked for me...
onTouchEnd={() => alert('TAPPED')}
The easiest way to do that:
<TouchableOpacity style={styles.container} onPress={()=> whateverFunc(parameter)}>
<Text style={styles.welcome}>
Tap to change the background
</Text>
</TouchableOpacity>
So, you need to replace the 'View' component to a 'TouchableOpacity' or any other Touchable component and you also need to replace the 'onClick' prop to 'onPress'. That's all. The wrapping of a view with a TouchableWhatever component is not necessary at all.

React-Native, Scroll View Not Scrolling

When I wrap content like this example below, it scrolls Perfectly..
return(
<ScrollView>
<Text> TEST </Text>
<Text> TEST </Text>
<Text> TEST </Text>
<Text> TEST </Text>
...
</ScrollView>
);
However, whenever I wrap it in another View, It will not scroll.
return(
<View>
<ScrollView>
<Text> TEST </Text>
<Text> TEST </Text>
<Text> TEST </Text>
<Text> TEST </Text>
...
</SCrollView>
</View>
);
Is there some sort of fix to this. I am trying to put a nav bar header above all of the content, couldn't really figure it out though.
It's a typo:
Your closing ScrollView tag is: </SCrollView> rather than </ScrollView>.
You also need to add a style to the View container, here's an example of what it should look like:
return(
<View style={{flex: 1}}>
<ScrollView>
<Text> TEST </Text>
<Text> TEST </Text>
<Text> TEST </Text>
<Text> TEST </Text>
...
</ScrollView>
</View>
);
Try next code:
<ScrollView contentContainerStyle={{ flexGrow: 1 }}>
<Text> TEST </Text>
<Text> TEST </Text>
<Text> TEST </Text>
<Text> TEST </Text>
</ScrollView>
If your ScrollView is within something that handles touch (Pressable, TouchableWithoutFeedback etc) then you either need to stop the touch event propagating up to that parent handler or else the ScrollView won't handle the touch event and therefore won't scroll.
This can be done either with onStartShouldSetResponder={() => true} or by wrapping the children in an element which itself handles the touch event (e.g. Pressable):
return (
<ScrollView>
<Pressable>
<Text>This is scrollable</Text>
<Pressable>
<Pressable>
<Text>As is this</Text>
<Pressable>
</ScrollView>
);
Try adding style={{flex:1}} to <View> and <ScrollView> components. You also have a typo on your code: </SCrollView> in line 9. An example code will look like this:
<View style={{backgroundColor:'white', flex:1}}>
<NavigationBar title="Title" />
<ScrollView style={{flex:1, backgroundColor:'white'}}>
<View style={{flex:1,justifyContent:'center'}}>
<RegisterForm />
</View>
</ScrollView>
</View>
Another solution is to add a height property to the parent View container. This sometimes works well when calculating the height against the screen height.
render () {
const screenHeight = Dimensions.get('window').height
return(
<View style={{height: screenHeight}}>
<ScrollView>
<Text> TEST </Text>
<Text> TEST </Text>
<Text> TEST </Text>
<Text> TEST </Text>
...
</ScrollView>
</View>
)
}
I have tried all of these solutions and none were working. Then I just fully restarted the app and the metro server and everything worked fine.
As #Evan Siroky has answered above it's working well I'm just adding on thing for a auto height in case you don't want to reserve the space
render () {
const screenHeight = Dimensions.get('window').height
return(
<View style={{ Height: "auto", maxHeight: screenHeight}}>
<ScrollView>
<Text> TEST </Text>
<Text> TEST </Text>
<Text> TEST </Text>
<Text> TEST </Text>
...
</ScrollView>
</View>
)
}
I had a similar issues, it got solved by removing height/width if set to '100%'.
Just adding here if someone faces the same issues. :D
Set nestedScrollEnabled as true for Hybrid Android + react app as it might be issue with gesture/click for scrolling issue.
Just if anyone is as desperate as I was:
My view was inside a StackNavigator. In the StackNavigator you can assign a default cardStyle. This card style needs height: "100%".
For me this was the case but I had overwritten it within the cardStyle of the Stack.Screen definition.
See this working example:
// This is the stack navigator
<ModalStack.Navigator screenOptions={() => ({
cardStyle: {height: "100%"}
});}}>
<ModalStack.Screen name={ScreenItemDetail} options={{
// cardStyle: {} be sure to not override card style again!
}} component={ItemDetailScreen} />
// ...
</ModalStack.Navigator>
removing contentContainerStyle prop from the ScrollView has fixed the issue for me
Just add ScrollView as parent View if it's still not working for you...just restart your app or server and your ScrollView will work fine. Because sometimes our app freezes for no reason.
I think the best way of doing this is to put all requires inside an array and map this array.
const images = [
require('../your/path/here'),
require('../other/image/here'),
...
];
return ( {images.map((image) => <Image ... source={image} />)
note that if you want it as a background image with other elements above the image, you may use BackgroundImage and either render elements for each image or position absolute the image map and zIndex it behind all things