React Native FlatList onPress for child - react-native

I'm trying to wire up a press handler for an image that's nested within a React Native FlatList. I've verified that the function is being passed in via props, by calling the function directly inside my component and that worked fine. Below is a reduced test case. I've also tried setting the onPress on the Image, with identical results.
const PostList = ({posts, onActLike, currentUser}) => {
return (
<FlatList
data={ posts }
keyExtractor={ (item) => item.id }
renderItem={ ({item}) => {
return (
<View>
<Image
source={ {uri: item.media.url} }
resizeMode="cover"
/>
<View>
<View
onPress={ (item) => {
onActLike(item);
} }
>
{
currentUser.likedMedia.indexOf(item.id) > -1 &&
<Image
source={ require('../assets/images/like_filled.png') }
style={ {width: 20, height: 17} }
resizeMode='contain'
/>
}
{
currentUser.likedMedia.indexOf(item.id) === -1 &&
<Image
source={ require('../assets/images/like_unfilled.png') }
style={ {width: 20, height: 17} }
resizeMode='contain'
/>
}
</View>
</View>
</View>
)
} }
/>
)
}

View doesn't accept an onPress function nor does Image. You need to wrap the View in a Touchable (TouchableOpacity, TouchableHighlight, etc)

Related

How to display particular image by clicking one flatlist images in react native?

I have a flat list that returns multiple images. but I want to show an image on another view by clicking FlatList image. when I click on FlatList image that particular image will be shown in another view. how to do please suggest.
Here is my FlatList:
<FlatList
data={this.state.images}
renderItem={this.renderGalleryImage}
keyExtractor={(item, index) => index}
horizontal={true}
/>;
renderGalleryImage = ({ item }) => {
return <Image source={item} style={styles.moreImg} />;
};
and here is the view where I want to display
<View>
</View>
You can approach this problem in several ways; The easiest way is to wrap the renderGalleryImage return statement with a Touchable primitive and add an onPress event handler.
You can use the useState hook in tandem to save the selected Image from the FlatList.
Here's a sample code snippet.
const [selectedItem, setSelectedItem] = useState("");
renderGalleryImage = ({ item }) => {
const setImage = () => setSelectedItem(item);
return (
<TouchableWithoutFeedBack onPress={() => setSelectedItem(item)}>
<Image source={item} style={styles.moreImg} />;
</TouchableWithoutFeedBack>
);
};
return <View>{selectedItem && <Image source={{ uri: selectedItem }} />}</View>;
Note: If you're using class-based components, follow this approach:
export default class App extends Component {
state = {
selectedImage: "",
};
renderGalleryImage = ({ item }) => {
const setImage = () => this.setState({ selectedImage: item.image });
return (
<TouchableWithoutFeedback onPress={setImage} style={{ margin: 30 }}>
<Image
source={{ uri: item.image }}
style={{ width: 100, height: 100 }}
/>
</TouchableWithoutFeedback>
);
};
render() {
const renderImage = () => (
<View>
<Image
source={{ uri: this.state.selectedImage }}
style={{ width: 100, height: 100,borderColor:'red',borderWidth:1 }}
/>
</View>
);
return (
<View>
<FlatList data={users} renderItem={this.renderGalleryImage} />;
<Text>Selected Image</Text>
{renderImage()}
</View>
);
}
}
Here's the link to a working demo on Expo.

Passing image from different activity and does show with require in an activity

This is my code i am run but image does not show after receiving the image source
render()
{const { navigation } = this.props;
const image = navigation.getParam('image',require('./add1.png'));
<View style={styles.rightFolderContent}>
<TouchableOpacity onPress={this.toggleSliderModal}>
<Image style={{height:68,width:77}} source={image} />
</TouchableOpacity>
</View>
}
You are not returning the Component in the render method.
Try this:
render()
{
const { navigation } = this.props;
const image = navigation.getParam('image',require('./add1.png'));
return (
<View style={styles.rightFolderContent}>
<TouchableOpacity onPress={this.toggleSliderModal}>
<Image style={{height:68,width:77}} source={image} />
</TouchableOpacity>
</View>
);
}

How to use if else condition inside nested map function in react-native?

I am making a react-native app that has a custom view like a grid view. All the cells of the view have same size except one. I want to give condition for the cell to have double the size from others.
I am making the view through an array using map function. Map function is not taking if statement. How should I use it?
// Buttons Array
buttons = [['1', '2', '3'],
['a', 'b', 'c'],
['q', 'w', 'e'],
['+', '-', '*'],
]
// '-' has double size...
import React, { Component } from 'react';
import {
View,
Text,
TouchableNativeFeedback
} from 'react-native';
//Styles
import styles from './styles';
export default class NumberButtons extends Component {
//This will call the bound function from its parent component
//to handle button press action/event
_handleOnPress = (value) => {
requestAnimationFrame(() => {
this.props.onBtnPress(value);
});
}
render() {
return (
<View style={styles.container}>
{
this.props.buttons.map((row, index) => (
<View key={index} style={styles.contRow}>
{
row.map((col,index) => (
//**** Here I want to use if else for row and column ***//
<TouchableNativeFeedback
key={index}
onPress={() => this._handleOnPress(col)}
background={TouchableNativeFeedback.SelectableBackground()}>
<View style={styles.buttonContainer}>
<Text style={styles.text}>{col}</Text>
</View>
</TouchableNativeFeedback>
))
}
</View>
))
}
</View>
);
}
}
You can render conditional views like this
<View style={styles.container}>
{this.state.buttons.map((row, index) => {
const myRow = row
console.log("myRow",myRow)
return (
<View key={index} style={styles.contRow}>
{
row.map((col,index) => {
if(col != 3 && myRow != null ){
return (
<TouchableNativeFeedback
key={index}
onPress={() => this._handleOnPress(col)}
background={TouchableNativeFeedback.SelectableBackground()}>
<View style={styles.buttonContainer}>
<Text style={styles.text}>{col}</Text>
</View>
</TouchableNativeFeedback>
)
}
else {
return (
<TouchableNativeFeedback
key={index}
onPress={() => this._handleOnPress(col)}
background={TouchableNativeFeedback.SelectableBackground()}>
<View style={styles.buttonContainer}>
<Text style={{backgroundColor:'#78909C'}}>{col}</Text>
</View>
</TouchableNativeFeedback>
)
}
})
}
</View>
)})
}
</View>
Here is the sample code how you can insert if and else in the nested map function.
this.props.availableEvents.map((item, i) => {
if (i < this.state.imageIndex) {
return null
} else if (i === this.state.imageIndex) {
return (
<Animated.View
{...this.imagePanResponder.panHandlers}
key={i}
style={[this.rotateAndTranslate, styles.cardContainer]}
>
<View style={{ width: '100%', height: '100%' }}>
</View>
</Animated.View>
)
} else {
return (
<Animated.View
key={i}
style={styles.cardContainer}>
<View style={{ width: '100%', height: '100%' }}>
</View>
</Animated.View>
)
}
}).reverse();
};

React Native TouchableHighlight not working with Sectionlist

I've got a SectionList, and for every row in the list I want to be able to detect a click event.
renderList() {
if (this.state.searching) {
return (
<SectionList
sections={this.state.data}
renderSectionHeader={this.props.renderSectionHeader}
renderItem={this.props.renderItem}
/>
);
}
return null;
}
render() {
return (
<View style={styles.container}>
<Animated.View
style={{ opacity: 1 - this.state.backgroundColor }}
pointerEvents={this.state.searching ? 'none' : undefined}
>
{this.props.children}
</Animated.View>
<Animated.View
style={[
styles.backgroundColorView,
{ opacity: this.state.backgroundColor },
]}
/>
<Animated.View
style={[styles.searchResults, { top: this.state.yPos }]}
>
<TextInput
ref={(input) => { this.searchBar = input; }}
style={styles.textInput}
value={this.props.query}
onChangeText={this.onChangeText}
maxLength={100}
placeholder={this.props.placeholder}
onFocus={this.onFocus}
onBlur={this.onUnSearch}
/>
{this.renderList()}
</Animated.View>
</View>
);
For my renderItem method, I'm passing in the following PureComponent, which is just a Text contained in a TouchableHighlight.
class SubjectSearchItem extends React.PureComponent {
render() {
const item = this.props.item;
return (
<TouchableHighlight
onPress={() => console.log(item)}
>
<View style={{
marginHorizontal: 20,
marginVertical: 10,
}}
>
<Text>{`${item.item.long_name} (${item.item.short_name})`}</Text>
</View>
</TouchableHighlight>
);
}
}
and here's the renderItem prop I'm passing in
const renderItem = item => (
<SubjectSearchItem
item={item}
/>
);
The problem is, no click events are being detected. The row isn't getting highlighted, and the onPress isn't being fired. Any ideas?
Note: seems like this has been an issue for a little while

Modal View in React Native

I am new to react native, I am trying to present a view modally. I have a table view and when one of the rows is clicked I want the view to show up modally.
This is how I am implementing the transition right now :
renderbooks(books) {
return (
<TouchableHighlight onPress={() => this.showbooksDetail(books)} underlayColor='#dddddd'>
<View>
<View style={styles.container}>
<View style={styles.rightContainer}>
<Text style={styles.title}>{books.title}</Text>
</View>
</View>
<View style={styles.separator} />
</View>
</TouchableHighlight>
);
}
showbooksDetail(books){
this.props.navigator.push({
title:books.title,
component: ProductView,
passProps:{books}
});
}
How can I modify this so that the view can be presented modally?
FYI: I have already looked at multiple questions and sample projects such as these:
How do I create a native looking modal view segue with react-native?
http://facebook.github.io/react-native/docs/modal.html#content
https://github.com/aaronksaunders/React-Modal-Nav-Example
Check out the built-in Modal. It's implemented on iOS, Android implementation should come in one of the next releases of React Native.
The documentation contains an example on how to use it.
In your case it would be something like:
renderBooks(books) {
...
<Modal
animated={true}
transparent={true}
visible={!!this.state.selectedBook}>
<Text>{this.state.selectedBook.title}</Text>
</Modal>
...
}
showDetail(book) {
this.setState({
selectedBook: book,
});
}
Check this simple and powerful small library react-native-modal-animated, simply install it by yarn add react-native-modal-animated, or npm install react-native-modal-animated.
import { AnimatedModal } from 'react-native-modal-animated
<View style={styles.container}>
<TouchableOpacity
onPress={() => {
this.setState({ modalVisible: true });
alert
}}
style={styles.button}
>
<Text style={styles.buttonText}>Show Modal</Text>
</TouchableOpacity>
<AnimatedModal
visible={this.state.modalVisible}
onBackdropPress={() => {
this.setState({ modalVisible: false });
}}
animationType="vertical"
duration={600}
>
{/*Any child can be used here */}
<View style={styles.modalCard}>
<Text>I'm AnimatedModal</Text>
<Text style={{fontWeight: 'bold', marginTop: 10}}>vertical</Text>
</View>
</AnimatedModal>
</View>
);
}
}
I am using the react-native modalbox. Its been awesome you get modals to be displayed in top,center,bottom,etc.Check the below link once:https://github.com/maxs15/react-native-modalbox
Sample:
import React from 'react';
import Modal from 'react-native-modalbox';
import Button from 'react-native-button';
import {
AppRegistry,
Text,
StyleSheet,
ScrollView,
View,
Dimensions
} from 'react-native';
class Example extends React.Component {
constructor() {
super();
this.state = {
isOpen: false,
isDisabled: false,
swipeToClose: true,
sliderValue: 0.3
};
}
onClose() {
console.log('Modal just closed');
}
onOpen() {
console.log('Modal just openned');
}
onClosingState(state) {
console.log('the open/close of the swipeToClose just changed');
}
render() {
return (
<View style={styles.wrapper}>
<Button onPress={() => this.refs.modal1.open()} style={styles.btn}>Basic modal</Button>
<Button onPress={() => this.refs.modal2.open()} style={styles.btn}>Position top</Button>
<Button onPress={() => this.refs.modal3.open()} style={styles.btn}>Position centered + backdrop + disable</Button>
<Button onPress={() => this.refs.modal4.open()} style={styles.btn}>Position bottom + backdrop + slider</Button>
<Modal
style={[styles.modal, styles.modal1]}
ref={"modal1"}
swipeToClose={this.state.swipeToClose}
onClosed={this.onClose}
onOpened={this.onOpen}
onClosingState={this.onClosingState}>
<Text style={styles.text}>Basic modal</Text>
<Button onPress={() => this.setState({swipeToClose: !this.state.swipeToClose})} style={styles.btn}>Disable swipeToClose({this.state.swipeToClose ? "true" : "false"})</Button>
</Modal>
<Modal style={[styles.modal, styles.modal2]} backdrop={false} position={"top"} ref={"modal2"}>
<Text style={[styles.text, {color: "white"}]}>Modal on top</Text>
</Modal>
<Modal style={[styles.modal, styles.modal3]} position={"center"} ref={"modal3"} isDisabled={this.state.isDisabled}>
<Text style={styles.text}>Modal centered</Text>
<Button onPress={() => this.setState({isDisabled: !this.state.isDisabled})} style={styles.btn}>Disable ({this.state.isDisabled ? "true" : "false"})</Button>
</Modal>
<Modal style={[styles.modal, styles.modal4]} position={"bottom"} ref={"modal4"}>
<Text style={styles.text}>Modal on bottom with backdrop</Text>
</Modal>
</View>
);
}
}
const styles = StyleSheet.create({
modal: {
justifyContent: 'center',
alignItems: 'center'
},
modal2: {
height: 230,
backgroundColor: "#3B5998"
},
modal3: {
height: 300,
width: 300
},
modal4: {
height: 300
},
wrapper: {
paddingTop: 50,
flex: 1
},
});
AppRegistry.registerComponent('Example', () => Example);