Images wont render - Struggling with 'react-native-snap-carousel' - react-native

unfortunately I am struggling to really grip how this library works, specifically the ParallaxImage component. I was wondering if someone could help me out. I am struggling to get my images to render.
Here are the docs: https://www.npmjs.com/package/react-native-snap-carousel#props-methods-and-getters
here is the following code but I also have a snack already running it here
It doesn't load on the web btw, you have to choose IOS or android.
import React, {useRef, useState, useEffect} from 'react';
import Carousel, {ParallaxImage} from 'react-native-snap-carousel';
import {
View,
Text,
Dimensions,
StyleSheet,
TouchableOpacity,
Platform,
} from 'react-native';
const ENTRIES1 = [
{
title: 'Text',
thumbnail: require('./assets/splash.png'),
},
{
title: 'Text 1',
thumbnail: require('./assets/splash.png'),
},
{
title: 'Text 2',
thumbnail: require('./assets/splash.png'),
},
];
const {width: screenWidth} = Dimensions.get('window');
const MyCarousel = props => {
const [entries, setEntries] = useState([]);
const carouselRef = useRef(null);
const goForward = () => {
carouselRef.current.snapToNext();
};
useEffect(() => {
setEntries(ENTRIES1);
}, []);
const renderItem = ({item, index}, parallaxProps) => {
return (
<View style={styles.item}>
<ParallaxImage
source={{uri: item.thumbnail}}
containerStyle={styles.imageContainer}
style={styles.image}
parallaxFactor={0.4}
{...parallaxProps}
/>
<Text style={styles.title} numberOfLines={2}>
{item.title}
</Text>
</View>
);
};
return (
<View style={styles.container}>
<Carousel
ref={carouselRef}
sliderWidth={screenWidth}
sliderHeight={screenWidth}
itemWidth={screenWidth - 60}
data={entries}
renderItem={renderItem}
hasParallaxImages={true}
/>
</View>
);
};
export default MyCarousel;
const styles = StyleSheet.create({
container: {
flex: 1,
},
item: {
width: screenWidth - 60,
height: screenWidth - 60,
},
imageContainer: {
flex: 1,
marginBottom: Platform.select({ios: 0, android: 1}), // Prevent a random Android rendering issue
backgroundColor: 'white',
borderRadius: 8,
},
image: {
...StyleSheet.absoluteFillObject,
resizeMode: 'cover',
},
});

I think you need to replace source={{uri: item.thumbnail}} with source={item.thumbnail}
because uri is used for web image url like https://image.png and require is used for the local image. I am tested on my android it's working fine now

Related

How to remove/replace default Profile Picture with Image Picker In React Native Expo

I am looking for assistance on how to replace a default profile picture with the one a user would select from their media library.
I have managed to create an onPress function that allows the user to select the image from their media library. The image is returned and displayed also in the prescribed layout.
My problem is that I cannot see the default profile picture, but I can see and click on a pencil icon to prompt the image-picker for iOS and Android as I am using Expo.
Here is my custom component code:
import React, { useState, useEffect } from "react";
import {
StyleSheet,
View,
Text,
Image,
TouchableOpacity,
useWindowDimensions,
Platform,
} from "react-native";
import { Controller } from "react-hook-form";
import * as ImagePicker from "expo-image-picker";
import { Ionicons } from "#expo/vector-icons";
//import dependencies
import { COLORS, SIZES, images } from "../constants";
const CustomImagePicker = ({ control, name, rules = {} }) => {
const { height } = useWindowDimensions();
const [hasGalleryPermission, setHasGalleryPermission] = useState("false");
const [profilePicture, setProfilePicture] = useState(name);
useEffect(() => {
async () => {
const galleryStatus =
await ImagePicker.requestMediaLibraryPermissionsAsync();
setHasGalleryPermission(galleryStatus.status === "granted");
};
}, []);
const pickImage = async () => {
let chosenImage = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.Images,
allowsEditing: true,
aspect: [4, 3],
quality: 1,
});
console.log(JSON.stringify(chosenImage));
if (!chosenImage.cancelled) {
setProfilePicture(chosenImage.uri);
}
};
if (hasGalleryPermission === false) {
return <Text>❌ No access to Internal Storage</Text>;
}
return (
<Controller
name={name}
control={control}
rules={rules}
render={({ field: { onChange, value }, fieldState: { error } }) => (
<>
<View
style={[
styles.container,
{ borderColor: error ? COLORS.red : COLORS.gray },
]}
>
<TouchableOpacity
style={styles.touchPicture}
onPress={() => pickImage()}
>
<Ionicons name="pencil-outline" size={24} color={COLORS.white} />
</TouchableOpacity>
<Image
onChange={onChange}
value={value}
source={{
uri: profilePicture ? profilePicture : images.defaultRounded,
}}
style={[
styles.logo,
styles.profileImage,
{ height: height * 0.19 },
]}
resizeMode={Platform.OS === "android" ? "contain" : "cover"}
/>
</View>
{error && (
<Text
style={{
color: COLORS.red,
alignSelf: "stretch",
fontSize: SIZES.body5,
padding: SIZES.padding - 22,
marginTop: 15,
marginHorizontal: SIZES.padding * 3,
}}
>
{error.message || "❌ Oops, something went wrong!"}
</Text>
)}
</>
)}
/>
);
};
export default CustomImagePicker;
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: "center",
alignItems: "center",
},
touchPicture: {
zIndex: 10,
marginBottom: -50,
marginLeft: 100,
resizeMode: "contain",
},
logo: {
width: Platform.OS == "android" ? 155 : 164,
maxWidth: 300,
maxHeight: 200,
},
profileImage: {
marginTop: SIZES.padding * 2,
borderRadius: 100,
},
});

Unable to Apply Layout Animation Using Reanimated API

I'm trying to apply layout animation to a FlatList upon adding and deleting a goal (list item) using the Reanimated API. I'm mainly following this tutorial from the Reanimated docs but I don't know why the animation is not applied when list items are added or removed. I should also inform that I'm only testing this on an Android device. Here is the code:
App.js (contains FlatList)
import { useState } from "react";
import { Button, FlatList, StyleSheet, View } from "react-native";
import GoalInput from "./components/GoalInput";
import GoalItem from "./components/GoalItem";
export default function App() {
const [goalList, setGoalList] = useState([]);
const [isModalOpen, setIsModalOpen] = useState(false);
const styles = StyleSheet.create({
appContainer: {
paddingTop: 50,
},
});
function startAddGoalHandler() {
setIsModalOpen(true);
}
// spread existing goals and add new goal
function addGoalHandler(enteredGoalText) {
setGoalList((currentGoals) => [
...currentGoals,
{ text: enteredGoalText, id: Math.random().toString() },
]);
}
function deleteGoalHandler(id) {
setGoalList((currentGoals) =>
currentGoals.filter((existingGoals) => existingGoals.id !== id)
);
}
return (
<View style={styles.appContainer}>
<Button
title='Add New Goal'
color='indigo'
onPress={startAddGoalHandler}
/>
{isModalOpen && (
<GoalInput
isModalOpen={isModalOpen}
setIsModalOpen={setIsModalOpen}
onAddGoal={addGoalHandler}
></GoalInput>
)}
<FlatList
keyExtractor={(item, index) => {
return item.id;
}}
data={goalList}
renderItem={(itemData) => {
return (
<GoalItem
onGoalDelete={deleteGoalHandler}
itemData={itemData}
/>
);
}}
/>
</View>
);
}
GoalItem.js (list item)
import React from "react";
import { Pressable, StyleSheet, Text } from "react-native";
import Animated, { Layout, LightSpeedInLeft, LightSpeedOutRight } from "react-native-reanimated";
const GoalItem = ({ itemData, onGoalDelete }) => {
const styles = StyleSheet.create({
goalCards: {
elevation: 20,
backgroundColor: "white",
shadowColor: "black",
height: 60,
marginHorizontal: 20,
marginVertical: 10,
borderRadius: 10,
},
});
return (
<Animated.View
style={styles.goalCards}
entering={LightSpeedInLeft}
exiting={LightSpeedOutRight}
layout={Layout.springify()}
>
<Pressable
style={{ padding: 20 }}
android_ripple={{ color: "#dddddd" }}
onPress={() => onGoalDelete(itemData.item.id)}
>
<Text style={{ textAlign: "center" }}>
{itemData.item.text}
</Text>
</Pressable>
</Animated.View>
);
};
export default GoalItem;
I've even tried replacing the FlatList with View but to no avail. I suspect that Reanimated isn't properly configured for my project, if I wrap some components with <Animated.View>...</Animated.View> (Animated from Reanimated and not the core react-native module) for example the child components will not show. Reanimated is installed through npm
Any help is appreciated, thanks!

ReactNative FlatList not rendering

I am new to ReactNative programming and .tsx files in general. I'm trying to display a basic FlatList and have copied the below code from the ReactNative docs here: (https://reactnative.dev/docs/flatlist). It's only slightly modified to fit into my ReactNative app which I am editing in Visual Studio code.
Does anyone know the correct way to display a FlatList? I've spent 2-3 days tinkering with this but I'm obviously missing some crucial ingredient. Beats me.
import * as React from "react";
import { useState, Component } from "react";
import EditScreenInfo from "../components/EditScreenInfo";
import { StyleSheet, Text, View, Dimensions, TouchableOpacity, Alert, FlatList, SafeAreaView, StatusBar } from "react-native";
// import PaymentScreen from "./PaymentScreen";
import { Driver } from "../models/Driver";
// tslint:disable-next-line:typedef
const styles = StyleSheet.create({
page: {
flex: 1,
justifyContent: "center",
alignItems: "center",
backgroundColor: "#FFF"
},
container: {
height: 750,
width: 750,
backgroundColor: "tomato"
},
map: {
flex: 1,
height:750,
width:750
},
item: {
padding: 10,
fontSize: 18,
height: 44,
},
title: {
fontSize: 18
}
});
// tslint:disable-next-line: typedef
const DATA = [
{
id: "bd7acbea-c1b1-46c2-aed5-3ad53abb28ba",
title: "First Item",
},
{
id: "3ac68afc-c605-48d3-a4f8-fbd91aa97f63",
title: "Second Item",
},
{
id: "58694a0f-3da1-471f-bd96-145571e29d72",
title: "Third Item",
},
];
// tslint:disable-next-line:typedef
const Item = ({ item, onPress, backgroundColor, textColor }: {
item: any;
onPress: any;
backgroundColor: any;
textColor: any;
}) => (
<TouchableOpacity onPress={onPress} style={[styles.item, backgroundColor]}>
<Text style={[styles.title, textColor]}>{item.title}</Text>
</TouchableOpacity>
);
export default class TabFourScreen extends Component {
drivers: Driver[] = []; // fetch these from backend... for now you can STUB
selectedId: any = useState(null);
setSelectedId: any = useState(null);
renderItem: any = ({ item }: {item: any}) => {
// tslint:disable-next-line:typedef
const backgroundColor = item.id === this.selectedId ? "#6e3b6e" : "#f9c2ff";
// tslint:disable-next-line:typedef
const color = item.id === this.selectedId ? "white" : "black";
return (
<Item
item={item}
onPress={() => this.setSelectedId(item.id)}
backgroundColor={{ backgroundColor }}
textColor={{ color }}
/>
);
}
render = () => {
return (
<View style={styles.page}>
<SafeAreaView style={styles.container}>
<FlatList
data={DATA}
renderItem={this.renderItem}
keyExtractor={(item) => item.id}
extraData={this.selectedId}
/>
</SafeAreaView>
</View>
);
}
}
First of all you can't use hooks like useState in a Class Component, you have to use Function Component: https://reactnative.dev/docs/getting-started#function-components-and-class-components.
Secondly, you have set width: 750 to your SafeAreaView's style, so the text doesn't appear on the screen you see but appears before.
Try this code:
import * as React from 'react';
import { useState, Component } from 'react';
import {
StyleSheet, Text, View, Dimensions, TouchableOpacity, Alert, FlatList, SafeAreaView, StatusBar,
} from 'react-native';
// import PaymentScreen from "./PaymentScreen";
// tslint:disable-next-line:typedef
const styles = StyleSheet.create({
page: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#FFF',
},
container: {
height: 750,
width: '100%',
backgroundColor: 'tomato',
},
map: {
flex: 1,
height: 750,
width: 750,
},
item: {
height: 44,
},
title: {
fontSize: 25,
color: 'white',
},
});
// tslint:disable-next-line: typedef
const DATA = [
{
id: 'bd7acbea-c1b1-46c2-aed5-3ad53abb28ba',
title: 'First Item',
},
{
id: '3ac68afc-c605-48d3-a4f8-fbd91aa97f63',
title: 'Second Item',
},
{
id: '58694a0f-3da1-471f-bd96-145571e29d72',
title: 'Third Item',
},
];
// tslint:disable-next-line:typedef
const Item = ({
item, onPress, backgroundColor, textColor,
}) => (
<TouchableOpacity onPress={onPress} style={[styles.item, backgroundColor]}>
<Text style={[styles.title, textColor]}>{item.title}</Text>
</TouchableOpacity>
);
const TabFourScreen = () => {
const [selectedId, setSelectedId] = useState(null);
const renderItem = ({ item }) => {
// tslint:disable-next-line:typedef
const backgroundColor = item.id === selectedId ? '#6e3b6e' : '#f9c2ff';
// tslint:disable-next-line:typedef
const color = item.id === selectedId ? 'white' : 'black';
return (
<Item
item={item}
key={item.id}
onPress={() => setSelectedId(item.id)}
backgroundColor={{ backgroundColor }}
textColor={{ color }}
/>
);
};
return (
<View style={styles.page}>
<SafeAreaView style={styles.container}>
<FlatList
data={DATA}
renderItem={renderItem}
keyExtractor={(item) => item.id}
extraData={selectedId}
/>
</SafeAreaView>
</View>
);
};
export default TabFourScreen;
I removed typescript just to test, feel free to add it again.
don't use this.renderItem use only renderItem

How to play list of videos sequentially by default without clicking next button accessing from local files of the device using react native cli

const filePath = `${dirs.DownloadDir}/samplevideos/1.mp4`;
const filePath1 = `${dirs.DownloadDir}/samplevideos/2.mp4`;
const paths = [{path:filePath},{path:filePath1}]
{paths&&paths.map((data,inx)=>{
return <Video key={inx} source={{uri:data.path }}
volume={50}
resizeMode="cover"
style={styles.videoStyle}
/>
})}
I have tried this but playing only last video. Any help will be appreciated.
I found solution for this question, So posting here it may help someone in the future.
there is a onEnd callback available in react-native-video based on that increasing index of next video
import React,{useEffect,useState} from 'react';
import {
StyleSheet,
View,
Image,
Text,
Dimensions,
PermissionsAndroid
} from 'react-native';
import Video from 'react-native-video';
import RNFetchBlob from 'rn-fetch-blob';
const FILE_PATHS = `${RNFetchBlob.fs.dirs.DownloadDir}/samplevideos/`;
const App = () => {
const [videoPaths,setVideosPath] = useState([]);
const [inxofCurrentVideo,setVideoIndex] = useState(0);
useEffect(() => {
PermissionsAndroid.RESULTS.GRANTED;
getVideoPaths();
},[])
const getVideoPaths = ()=>{
RNFetchBlob.fs.ls(FILE_PATHS).then(files => {
setVideosPath(files);
}).catch(error => console.log(error))
};
const onEnd =()=> {
if((inxofCurrentVideo < videoPaths.length) || (videoPaths.length === inxofCurrentVideo)){
setVideoIndex(inxofCurrentVideo+1);
}
}
return (
<View style={styles.videoContainer}>
<View style={styles.row}>
{videoPaths.length>0&&<Video onEnd = {onEnd}
source={{uri:(FILE_PATHS + videoPaths[inxofCurrentVideo])}}
volume={50}
resizeMode="cover"
style={styles.videoStyle}
/> }
</View>
</View>
);
};
const styles = StyleSheet.create({
videoContainer: {
flex: 1,
// backgroundColor: 'black',
},
row: {
flex: 1,
flexDirection: "row",
width: '100%'
},
col6: {
width: "50%"
},
videoStyle: {
position: 'absolute',
top: 0,
bottom: 5,
left: 0,
right: 0,
},
});
export default App;

React-Native: Is it possible to get the layout positions of the FlatList

As I indicated in the Picture with arrow mark, I would like to get the top positions of FlatList. I tried onLayout props, But it return only null values.
Is there anyway to get the top positions of FlatList?
Check below sample
import React, {Component} from 'react';
import {View, FlatList, StyleSheet, Text} from 'react-native';
const DATA = [
{
id: 'bd7acbea-c1b1-46c2-aed5-3ad53abb28ba',
title: 'First Item',
},
{
id: '3ac68afc-c605-48d3-a4f8-fbd91aa97f63',
title: 'Second Item',
},
{
id: '58694a0f-3da1-471f-bd96-145571e29d72',
title: 'Third Item',
},
];
export default class HomeScreen extends Component {
findDimesions = layout => {
const {x, y, width, height} = layout;
console.log(x);
console.log(y);
console.log(width);
console.log(height);
};
render() {
return (
<View
onLayout={event => this.findDimesions(event.nativeEvent.layout)}
style={styles.container}>
<FlatList
data={DATA}
renderItem={({item}) => (
<View style={styles.item}>
<Text style={styles.title}>{item.title}</Text>
</View>
)}
keyExtractor={item => item.id}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
item: {
backgroundColor: '#f9c2ff',
padding: 20,
marginVertical: 8,
marginHorizontal: 16,
},
title: {
fontSize: 32,
},
});
Change this according to your requirements.
Hope this helps you. Feel free for doubts.
return (
<View style={styles.container}>
<SafeAreaView style={styles.top} />
<FlatList
...
/>
</View>
);
}
const styles = StyleSheet.create({
top: { flex: 0 },
}