How to scroll images horizontally having two columns upper row contain even images and lower row contain odd images - react-native

Hii I want to scroll images horizontally having two columns upper row contain even images and lower row contain odd images, but i dont know how to do this
code to fetch api
componentDidMount(){
return fetch('https://www.json-generator.com/api/json/get/ccLAsEcOSq?indent=1')
.then((response) => response.json())
.then((responseJson) => {
this.setState({
isLoading: false,
dataSource: responseJson.book_array,
}, function(){
});
})
.catch((error) =>{
console.error(error);
});}
code for render
render() {
if (this.state.isLoading === true) {
return <ActivityIndicator color={'red'} />;
}
return (
<View style={styles.container}>
<ScrollView horizontal={true} contentContainerStyle={{height:300, flexWrap:'wrap'}}>
{this.state.dataSource.map(item => this.renderItem(item))}
</ScrollView>
</View>
);
}
}
code for renderItem
renderItem(item) {
return (
<View style={{ margin: 5 }}>
<View style={{
backgroundColor: 'red',
width: 150,
height: 150,
marginBottom: 1,
}}>
<Image style={{ width: 150,height: 150}}
source={{uri: item.image}}/>
</View>
<View style={{
backgroundColor: 'red',
width: 150,
height: 150,
marginBottom: 1,
}}>
<Image style={{ width: 150,height: 150}}
source={{uri: item.image}}/>
</View>
</View>
);
}

Related

react-native-video inside flatlist showing black screen after scrolling some videos

I am developing a flatlist with full screen videos like tiktok, it works fine for first 16/17 videos then when I scroll further it shows black screen.
Following is my code for the flatlist:
<FlatList
style={{
width: width,
height: this.state.videoHeight,
}}
getItemLayout={(data, index) => ({
length: this.state.videoHeight,
offset: this.state.videoHeight * index,
index,
})}
onScrollToIndexFailed={(info) => {
const wait = new Promise((resolve) =>
setTimeout(resolve, 500),
);
wait.then(() => {
this.flatlistRef.current?.scrollToIndex({
index: info.index,
animated: false,
});
});
}}
showsVerticalScrollIndicator={false}
data={this.state.allVideos}
ref={this.flatlistRef}
scrollEnabled={!this.state.isMinimizePlayer}
viewabilityConfig={this.viewabilityConfig}
decelerationRate={0}
removeClippedSubviews={true}
snapToAlignment={'start'}
snapToInterval={this.state.videoHeight}
horizontal={false}
onViewableItemsChanged={this.onViewableItemsChanged}
renderItem={this.renderItem}
keyExtractor={(item, index) => item.id}
/>
Render function code
renderItem = ({item, index}) => (
<PlayerContext.Consumer>
{({setVideo, setMetaData}) => (
<TouchableOpacity
onPress={() => {
if (!this.state.isMinimizePlayer) {
this.setState({isPause: !this.state.isPause});
} else {
this.maximizePlayr();
}
}}
activeOpacity={0.9}
style={{
width: width,
height: this.state.videoHeight,
}}>
<Video
// hideShutterView={false}
// useTextureView={true}
ref={(ref) => {
this.playerRef[index] = ref;
}}
style={{
backgroundColor: 'black',
width: this.state.videoWidth,
height: this.state.videoHeight,
}}
resizeMode={'cover'}
muted={this.state.isMute}
paused={
index == this.state.currentVisibleIndex
? this.state.isPause
: true
// index !== this.state.currentVisibleIndex ||
// !this.state.isPause
}
onLoad={(data) => {
// console.log('===>' + index);
}}
controls={false}
hideShutterView={true}
repeat={this.state.isLoop}
onEnd={() => {
if (!this.state.isLoop) {
if (this.state.isAutoPlay) {
if (
this.state.currentVisibleIndex <
this.state.allVideos.length - 1
) {
if (this.state.setGoNext) {
this.setState({setGoNext: false});
this._goToNextPage();
setTimeout(() => {
this.setState({setGoNext: true});
}, 1000);
}
} else {
setVideo(null);
}
}
}
}}
onProgress={(progress) => {
if (this.state.currentTrackDuration == 0) {
this.setState({
currentTrackDuration: progress.seekableDuration,
});
}
this.setState({
progress: progress.currentTime / progress.seekableDuration,
});
}}
bufferConfig={{
minBufferMs: 15000,
maxBufferMs: 50000,
bufferForPlaybackMs: 1500,
bufferForPlaybackAfterRebufferMs: 1500,
}}
source={{uri: item.url}}
poster={item.url}
onError={(e) => console.log('video load failed!' + index, e)}
onVideoError={(e) =>
console.log('video error load failed!' + index, e)
}
onReadyForDisplay={() => {}}
posterResizeMode={'cover'}></Video>
{this.state.isMinimizePlayer && (
<View
style={{
backgroundColor: this.ThemedColors.happy,
position: 'absolute',
width: this.state.videoWidth,
justifyContent: 'center',
alignItems: 'center',
height: this.state.videoHeight,
}}>
<TouchableOpacity
onPress={() => {
this.setState({isPause: !this.state.isPause});
}}>
<IconM
name={!this.state.isPause ? 'play-arrow' : 'pause'}
size={28}
color={'white'}
/>
</TouchableOpacity>
</View>
)}
{this.state.isMinimizePlayer && (
<View
style={{
flexDirection: 'row',
flex: 1,
height: this.state.videoHeight,
justifyContent: 'space-between',
alignItems: 'center',
top: 0,
bottom: 0,
left: 110,
position: 'absolute',
right: 10,
}}>
<View
style={{
flex: 1,
paddingHorizontal: 10,
justifyContent: 'center',
}}>
<Text style={{}} numberOfLines={1}>
{item.name}
</Text>
<View
style={{
marginTop: 5,
flexDirection: 'row',
paddingLeft: 0,
alignItems: 'center',
}}>
<Image
source={require('../../../assets/Images/icon_eye.png')}
style={{
height: 10,
width: 16,
tintColor: 'black',
resizeMode: 'contain',
}}
/>
<Text style={{marginLeft: 2}}>{this.metaData.from}</Text>
</View>
</View>
<TouchableOpacity
onPress={() => {
setVideo(null);
}}
style={{
height: 50,
width: 50,
alignItems: 'center',
justifyContent: 'center',
}}>
<Icon name="close" size={20} color={'black'} />
</TouchableOpacity>
</View>
)}
{!this.state.isMinimizePlayer && (
<LinearGradient
colors={['#000000', '#80000000']}
style={{
position: 'absolute',
top: 0,
paddingTop: Platform.OS == 'ios' ? width * 0.1 : width * 0.04,
left: 0,
right: 0,
}}>
<Text style={this.ThemedStyles.videoTitleText} numberOfLines={1}>
{item.name}
</Text>
<View style={this.ThemedStyles.videoMomentContaine}>
<Text style={this.ThemedStyles.videoDateText}>
{moment.unix(item.createdAt / 1000).format('MMMM DD, YYYY')}
</Text>
<Text
style={[
this.ThemedStyles.videoMomentText,
{backgroundColor: this.ThemedColors[item.moment]},
]}>
{item.moment}
</Text>
</View>
<View style={this.ThemedStyles.videoMomentTagContaine}>
{item?.tagN?.map((data) => {
return (
<View>
<Text style={this.ThemedStyles.videoDateText}>
#{data}
</Text>
</View>
);
})}
</View>
</LinearGradient>
)}
</TouchableOpacity>
)}
</PlayerContext.Consumer>
);
When scrolling it works and playing videos for first 16 videos then it show black screen for next videos and not playing them. When scrolling back to previous videos they are still playing but videos after 16th are black.

Last odd flatlist item stretches along screen

I'm displaying some data items with Flatlist in two columns. But when there is an odd item at the last place, it stretches all along the screen. I don't want that, how can I make it to take only %50 of screen space like even items? Thanks a lot.
CategoryGridTile Component:
return (
<View style={styles.PlaceItem}>
<TouchableCmp onPress={props.onSelect}>
<View>
<View style={{ ...styles.placeRow, ...styles.placeHeader }}>
<ImageBackground
source={{ uri: props.image }}
style={styles.bgImage}
>
<View style={styles.titleContainer}>
<Text style={styles.title} numberOfLines={2}>
{props.title}
</Text>
</View>
</ImageBackground>
</View>
</View>
</TouchableCmp>
</View>
)
}
const styles = StyleSheet.create({
PlaceItem: {
flex: 1,
height: 125,
width: '80%',
backgroundColor: '#f5f5f5',
borderRadius: 5,
overflow: 'hidden',
margin: 6
},
placeRow: {
flexDirection: 'row'
}
})
Screen:
const renderGridItem = itemData => {
return (
<CategoryGridTile
image={itemData.item.image}
title={itemData.item.title}
onSelect={() => {
props.navigation.navigate({
routeName: 'CategoryPlaces',
params: {
categoryId: itemData.item.title,
locationId: locations
}
})
}}
/>
)
}
return (
<FlatList
keyExtractor={(item, index) => item._id}
data={displayedCategories}
renderItem={renderGridItem}
numColumns={2}
/>
)
Changing PlaceItem flex: 1 to flex: 1/2 at CategoryGridTile component solved the problem.

Access state data in other component

Hi how can I access the state where I'm fetching all the data in an other component ? I have a component Accueil where I'm fetching the data and a component UserItem where I'm styling and showing the info. So I'm in my Accueil component I have a flatlist and inside this flatlist in the renderItem function I'm passing the . So how can I access the state dataSource in UserItem ?
class UserItem extends React.Component {
render() {
const user = this.props.user;
const displayDetailForUser = this.props.displayDetailForUser;
var colorConnected;
if (user.Statut == "ON") {
colorConnected = "#1fbc26";
}
else if (user.Statut == "OFF") {
colorConnected = "#ff0303";
}
else {
colorConnected = "#ffd200";
}
return (
<TouchableOpacity style={styles.view_container} onPress={() =>
displayDetailForUser(user.MembreId, user.Pseudo, user.Photo, user.Age, user.Genre, user.Description, user.distance, user.Statut, user.localisation, user.principale )}>
<ImageBackground source={{ uri : user.Photo}} style={{ flex: 1, aspectRatio: 1, position: 'relative', borderColor: '#d6d6d6', borderWidth: 1}}>
<View style={[styles.bulle_presence, { backgroundColor: colorConnected } ]}></View>
<TouchableOpacity>
<Image style = {{aspectRatio:0.6, position:'absolute', resizeMode:'contain', height:40, width:40, right:15, top:15 }} source = {require("../Images/chat-bg.png")}/>
</TouchableOpacity>
</ImageBackground>
<View style={{ backgroundColor: '#d6d6d6', padding: 6 }}>
<View style={{ flexDirection: 'row', alignItems: 'center' }}>
<View>
<Text style={{ fontSize: 25 }}>{user.Age}</Text>
</View>
<View style={{ marginRight: 7, marginLeft: 7, backgroundColor: '#000000', width: 1, height: 26 }}></View>
<View style={{ flexDirection: 'column', flex:1 }}>
<Text style={{ fontSize: 13, fontWeight: '600' }}>{user.Pseudo}</Text>
<View style={{ flexDirection: 'row', justifyContent: 'space-between'}}>
<Text style={{ fontSize: 12 }}>{user.distance}</Text>
<Text style={{ fontSize: 12 }}>{user.Genre}</Text>
</View>
</View>
</View>
</View>
</TouchableOpacity>
)
}
}
I've tried with const user = this.props.dataSource but it's not working. Thanks
Edit:
lass Accueil extends React.Component {
constructor(props) {
super(props);
this.state = {
loading: false,
refreshing: false,
location: null,
latitude:null,
longitude:null,
dataSource:[]
}
this.displayPosition = this.displayPosition.bind(this);
}
handleRefresh = () => {
this.setState (
{
refreshing: true,
},
() => {
setTimeout(() => {this.setState({refreshing: false,})}, 1000)
}
);
};
componentDidMount() {
const url = "SomeUrl";
fetch(url)
.then(res => res.json())
.then(res => {
this.setState({
dataSource: res
});
})
.catch(error => {
console.log("get data error:" + error);
});
}
static navigationOptions = ({ navigation }) => {
return {
headerRight: () => (
<View style={{marginLeft: 8, marginRight: 8, flexDirection: 'row', alignItems: 'center' }}>
<TouchableOpacity style={{ marginRight: 10 }} onPress={ () =>{ }}>
<Image style={{ width: 22, height: 22 }} source={require("../Images/search.png")} />
</TouchableOpacity>
<TouchableOpacity style={{marginLeft: 10, marginRight: 10 }} onPress={ () =>{{this.displayPosition()}}}>
<Image style={{ width: 22, height: 22 }} source={require("../Images/localisation.png")} />
</TouchableOpacity>
<TouchableOpacity style={{marginLeft: 10 }} onPress={ () =>{ }}>
<Image style={{ width: 22, height: 22 }} source={require("../Images/refresh.png")} />
</TouchableOpacity>
</View>
),
};
};
displayPosition = () => {
Geolocation.getCurrentPosition(
(position) => {
this.setState({
latitude: JSON.stringify(position.coords.latitude),
longitude: JSON.stringify(position.coords.longitude),
error: null,
});
console.log(this.state.latitude)
},
(error) => this.setState({ error: error.message }),
{ enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 },
);
}
_displayDetailForUser = (idUser, name, photo, age, pratique, description, distance, Statut, localisation, principale ) => {
//console.log("Display user with id " + idUser);
this.props.navigation.navigate("UserProfil", { idUser: idUser, name:name, photo: photo, age:age, pratique:pratique, description:description, distance:distance, Statut:Statut, localisation:localisation, principale:principale });
}
render() {
return (
<SafeAreaView style={{ flex:1 }}>
<View style={styles.main_container}>
<FlatList style={styles.flatList}
data={this.state.dataSource}
keyExtractor={(item) => item.MembreId}
renderItem={() => <UserItem user={this.state.dataSource} displayDetailForUser={this._displayDetailForUser} />}
numColumns={numColumns}
refreshing={this.state.refreshing}
onRefresh={this.handleRefresh} />
</View>
</SafeAreaView>
)
}
}

how to Use if in FlatList

I have array which has images. I want to give show images in flatlist everything is ok now. But I want to show some of them I mean if condition is true show that image.
this is my code:
renderItem={ ({ item }) =>
{
if (true) {
<View style={{ width: '22%', marginLeft: '3%', marginTop: '2%', alignItems: 'center' }} >
<TouchableOpacity onPress={() => this.props.navigation.navigate('DescriptionPage', { data: item.call })}>
<ImageBackground source={item.img} style={{ width: 60, height: 60 }} />
</TouchableOpacity>
</View>
}
else {
...
}
}
}
if I use like this there is no error and it shows all images.
<FlatList
data={images}
keyExtractor={(item, index) => index.toString()}
numColumns={4}
renderItem={ ({ item }) =>
<View style={{ width: '22%', marginLeft: '3%', marginTop: '2%', alignItems: 'center' }} >
<TouchableOpacity onPress={() => this.props.navigation.navigate('DescriptionPage', { data: item.call })}>
<ImageBackground source={item.img} style={{ width: 60, height: 60 }} />
</TouchableOpacity>
</View>
}
/>
There is mistake here I dont know why :
{
if (true)
{
...
}
else
{
...
}
}
you forgot to add return inside if else condition:
do it like this:
renderItem={ ({ item }) =>
{
if (true) {
// add return
return(
<View style={{ width: '22%', marginLeft: '3%', marginTop: '2%', alignItems: 'center' }} >
<TouchableOpacity onPress={() => this.props.navigation.navigate('DescriptionPage', { data: item.call })}>
<ImageBackground source={item.img} style={{ width: 60, height: 60 }} />
</TouchableOpacity>
</View>
)
}
else {
// add return
return(
...
)
}
}
}
Just use this kind of setup:
return (isTrue) ?
<TouchableOpacity onPress={() => this.props.navigation.navigate('DescriptionPage', { data: item.call })}>
<ImageBackground source={item.img} style={{ width: 60, height: 60 }} />
</TouchableOpacity> : null;
This should render the component if it is true, else, it won't render anything.

How to show Scrollview images horizontally having 2 columns

Hii i want to display images horizontally having 2 columns for this i am using scrollview but i dont know how to do that , i am using following code
code to fetch api
componentDidMount(){
return fetch('https://www.json-generator.com/api/json/get/ccLAsEcOSq?indent=1')
.then((response) => response.json())
.then((responseJson) => {
this.setState({
isLoading: false,
dataSource: responseJson.book_array,
}, function(){
});
})
.catch((error) =>{
console.error(error);
});
}
code for render
render() {
if (this.state.isLoading === true) {
return <ActivityIndicator color={'red'} />;
}
return (
<View style={styles.container}>
<ScrollView horizontal={true}>
{this.state.dataSource.map(item => this.renderItem(item))}
</ScrollView>
</View>
);
}
}
code for renderItem
renderItem(item) {
return (
<View style={{ margin: 5 }}>
<View style={{
backgroundColor: 'red',
width: 150,
height: 150,
marginBottom: 1,
}}>
<Image style={{ width: 150,height: 150}}
source={{uri: item.image}}/>
</View>
<View style={{
backgroundColor: 'red',
width: 150,
height: 150,
marginBottom: 1,
}}>
<Image style={{ width: 150,height: 150}}
source={{uri: item.image}}/>
</View>
</View>
);}
Instead of ScrollView try FlatList which provides numColumns props which lets you allow to use columns as per your choice.
Instead of this,
<ScrollView horizontal={true}>
{this.state.dataSource.map(item => this.renderItem(item))}
</ScrollView>
Use this,
<FlatList
data={this.state.dataSource}
numColumns={2}
renderItem={this.renderItem}
/>
For more details of FlatList see Official Docs Here
Try flex-direction property:
renderItem(item) {
return (
<View style={{ margin: 5, flex: 1, flexDirection: "row", justifyContent: "space-around" }} >
<View style={{ backgroundColor: "red", width: 150, height: 150, marginBottom: 1 }} >
<Image style={{ width: 150, height: 150 }} source={{ uri: item.image }} />
</View>
<View style={{ backgroundColor: "red", width: 150, height: 150, marginBottom: 1 }} >
<Image style={{ width: 150, height: 150 }} source={{ uri: item.image }} />
</View>
</View>
);}
modify your ScrollView component Like this:
<ScrollView horizontal={true} contentContainerStyle={{height:300, flexWrap:'wrap'}}>
{this.state.dataSource.map(item => this.renderItem(item))}
</ScrollView>
Use flat list inside scroll view like this
<FlatList
horizontal={true}
data={this.state.dataSource}
renderItem={({ item }) => (this.renderItem({item}))}
/>
rearrange dataSource like this
array1 = [obj1,obj2,obj3,obj4,obj5,obj6,obj7,
array2=[[obj1,obj2],[obj3,obj4],[obj5,obj6],[obj7,obj8]]
and then render item with 2 rows.
didn't find any other way
To create view as you required need to implement your custom logic. In render function call a intermediate function to get columns in two row:
render() {
if (this.state.isLoading === true) {
return <ActivityIndicator color={'red'} />;
}
return (
<View style={styles.container}>
<ScrollView horizontal={true}>
{this.renderHorizantol(this.state.dataSource)}
</ScrollView>
</View>
);
In renderHorizantol function need to set up logic for even or odd rows, i am implementing this on index of dataSource Array:
renderHorizantol = (dataSource) =>{
let view = []
for(let i=0 ; i < data.length ; i = i+2)
{
let subView = this.renderItem(dataSource[i],dataSource[i+1])
view.push(subView)
}
return view
}
In renderItem function pass two element to draw upper and lower row contents:
renderItem(item1,item2) {
let image1 = item1["imageUrl"]
let image2 = item2 ? item2["imageUrl"] : null
return (
<View style={{ margin: 5 }}>
<View style={{
backgroundColor: 'red',
width: 150,
height: 150,
marginBottom: 1,
}}>
<Image style={{ width: 150,height: 150}}
source={{uri: image1}}/>
</View>
<View style={{
backgroundColor: 'red',
width: 150,
height: 150,
marginBottom: 1,
}}>
<Image style={{ width: 150,height: 150}}
source={{uri: image2}}/>
</View>
</View>
);}