I am using react-native-swiper-flatlist , but my image is not displaying i don't know error - react-native

// My deals
const Deals =[{
id:'1',
imageUrl:
'https://upload.wikimedia.org/wikipedia/commons/thumb/2/20/Spaghetti_Bolognese_mit_Parmesan_oder_Grana_Padano.jpg/800px-Spaghetti_Bolognese_mit_Parmesan_oder_Grana_Padano.jpg',
},
{
id:'2',
imageUrl:
'https://upload.wikimedia.org/wikipedia/commons/thumb/2/20/Spaghetti_Bolognese_mit_Parmesan_oder_Grana_Padano.jpg/800px-Spaghetti_Bolognese_mit_Parmesan_oder_Grana_Padano.jpg',
},
{
id:'3',
imageUrl:
'https://upload.wikimedia.org/wikipedia/commons/thumb/2/20/Spaghetti_Bolognese_mit_Parmesan_oder_Grana_Padano.jpg/800px-Spaghetti_Bolognese_mit_Parmesan_oder_Grana_Padano.jpg',
},
{
id:'4',
imageUrl:
'https://upload.wikimedia.org/wikipedia/commons/thumb/2/20/Spaghetti_Bolognese_mit_Parmesan_oder_Grana_Padano.jpg/800px-Spaghetti_Bolognese_mit_Parmesan_oder_Grana_Padano.jpg',
},
]
export default () => {
return (
<SwiperFlatList
autoplay
autoplayDelay={5}
index={3}
autoplayLoop
autoplayInvertDirection
data={Deals}
renderItem={ Deals => { return <Image style={styles.image} source={{uri:Deals.imageUrl}} />}}
showPagination
PaginationComponent={CustomPagination}
/>
);
};
const styles = StyleSheet.create ({
image: {
height: height * 0.5,
width,
},
});

I think your problem is with the image style.
instead of this:
image: {
height: height * 0.5,
width,
},
try setting fixed values, or window-size related values, like:
image: {
height: Dimensions.get('window').height * 0.5,
width: Dimensions.get('window').width,
}

Related

How to show 2 items in one pagination of react native snap carousel

How to dispaly 2 items for one pagination(first dot) and if we swipe then next 2 items should display with showing second dot active.
And if it is odd then last item should display my own component in react native snap carousel.
I would suggest that you go ahead and make the item you're rendering in the Carousel one that renders 2 things at once. The Carousel will paginate on whatever you pass to it, so if you're passing something with 2 items in it, it'll paginate on that, so for example:
<Carousel
layout="default"
data={arr}
renderItem={
({ item, index }) => (
<View style={styles.imageWrapper}>
<Image
style={styles.image}
source={item[0]}
resizeMode="cover"
accessibilityLabel="thumbnail"
/>
<Image
style={styles.image}
source={item[1]}
resizeMode="cover"
accessibilityLabel="thumbnail"
/>
</View>
)
}
lockScrollWhileSnapping={true} // Prevent the user from swiping again while the carousel is snapping to a position.
sliderWidth={screenWidth}
sliderHeight={screenWidth * 0.5}
itemWidth={screenWidth - 40}
activeSlideOffset={50}
enableSnap
onSnapToItem={onSnapToItem}
removeClippedSubviews={false}
firstItem={0}
contentContainerCustomStyle={styles.style}
/>
Create a function that split "entries" array into smaller arrays based on the size that you want
var slides = [];
const entriesSplitter = () => {
let size = 2; //Based on the size you want
while (entries.length > 0) {
slides.push(entries.splice(0, size));
}
};
then pass the slides array to <Carousel data={slides}/> then render each slide
in _renderItem
consider the following example:-
import React, { useState, useRef } from "react";
import { View,Text, Dimensions } from "react-native";
import Carousel, { Pagination } from "react-native-snap-carousel";
const { width: screenWidth, height: screenHeight } = Dimensions.get("window");
const myCarousel = () => {
const [activeSlide, setActiveSlide] = useState(0);
const carousel = useRef();
const entries = [
{
title: "Adidas"
},
{
title: "Nike"
},
{
title: "Puma"
},
{
title: "Reebok"
}
];
var slides = [];
const entriesSplitter = () => {
let size = 2; //Based on the size you want
while (entries.length > 0) {
slides.push(entries.splice(0, size));
}
};
// render every single slide
const _renderItem = ({ item,index }) => {
return (
<View style={{ flexDirection: "row", flexWrap: "wrap" }}>
{item.map(item => {
return <Text key={index}>{item.title}</Text>;
})}
</View>
);
};
return (
<View>
{entriesSplitter()}
<Carousel
ref={carousel}
data={slides}
renderItem={_renderItem}
onSnapToItem={index => setActiveSlide(index)}
sliderWidth={screenWidth}
sliderHeight={screenHeight}
itemWidth={screenWidth}
/>
<Pagination
dotsLength={2} // also based on number of sildes you want
activeDotIndex={activeSlide}
containerStyle={{ backgroundColor: "red", borderWidth: 2 }}
dotStyle={{
width: 10,
height: 10,
borderRadius: 5,
marginHorizontal: 8,
backgroundColor: "black"
}}
inactiveDotStyle={{
backgroundColor: "pink"
}}
inactiveDotOpacity={0.4}
inactiveDotScale={0.6}
/>
</View>
);
};
export default myCarousel;
This is how I implemented to show 3 carousels. We can customize it in many ways
import React from "react";
import { View, Dimensions, StyleSheet, Image } from "react-native";
import Carousel from "react-native-snap-carousel";
const windowWidth = Dimensions.get("window").width;
export default function MyCarousel() {
const images = [
{ id: 1, image: require("../assets/home-slider-1.jpg") },
{ id: 2, image: require("../assets/home-slider-2.jpg") },
{ id: 3, image: require("../assets/home-slider-3.jpg") },
{ id: 4, image: require("../assets/home-slider-4.jpg") }
];
// const imagesUri = [
// { id: 1, image: { uri: 'https://i.imgur.com/gG5Egof.jpg' } },
// { id: 2, image: { uri: 'https://i.imgur.com/gG5Egof.jpg' } },
// { id: 3, image: { uri: 'https://i.imgur.com/gG5Egof.jpg' } },
// { id: 4, image: { uri: 'https://i.imgur.com/gG5Egof.jpg' } }
// ];
const _renderItem = ({ item }) => {
return (
<View style={styles.slide}>
<Image
source={item.image}
style={styles.image}
// resizeMode="center"
></Image>
</View>
);
};
return (
<View style={styles.wrapper}>
<Carousel
data={images}
renderItem={_renderItem}
sliderWidth={windowWidth}
itemWidth={windowWidth - 70}
enableMomentum={false}
lockScrollWhileSnapping
autoplay
useScrollView
loop
autoplayInterval={3000}
/>
</View>
);
}
const styles = StyleSheet.create({
wrapper: {
height: 150
},
slide: {
flex: 1,
justifyContent: "center",
alignItems: "center",
backgroundColor: "#fff"
},
image: {
flex: 1,
height: "100%",
width: "100%",
alignItems: "center",
justifyContent: "center"
}
});

Animated element display not updated after position change

I'm fairly new to React-Native, so it's very likely I'm missing some core concepts.
I want to create a draggable element and be able to move it back to its original position.
The first part is ok, but when I try to update the position, it looks like it works (because when I click again, the element goes back to its original position), but the view isn't updated.
I tried calling setState and forceUpdate but it doesn't update the view.
Do you guys have any idea why ?
Here is a demo of what I have so far :
import React from 'react';
import {Button, StyleSheet, PanResponder, View, Animated} from 'react-native';
export default class Scene extends React.Component {
constructor(props) {
super(props)
const rectanglePosition = new Animated.ValueXY({ x: 0, y: 0 })
const rectanglePanResponder = this.createPanResponder();
this.state = {
rectanglePosition,
rectanglePanResponder
}
}
createPanResponder = () => {
return PanResponder.create({
onStartShouldSetPanResponder: () => true,
onPanResponderMove: (event, gesture) => {
this.state.rectanglePosition.setValue({ x: gesture.dx, y: gesture.dy });
},
onPanResponderRelease: () => {
this.state.rectanglePosition.flattenOffset();
},
onPanResponderGrant: () => {
this.state.rectanglePosition.setOffset({
x: this.state.rectanglePosition.x._value,
y: this.state.rectanglePosition.y._value
});
}
});
}
resetPosition = () => {
const newPosition = new Animated.ValueXY({ x: 0, y: 0 })
this.setState({ rectanglePosition: newPosition }) // I thought updating the state triggered a re-render
this.forceUpdate() // doesn't work either
}
getRectanglePositionStyles = () => {
return {
top: this.state.rectanglePosition.y._value,
left: this.state.rectanglePosition.x._value,
transform: this.state.rectanglePosition.getTranslateTransform()
}
}
render() {
return (
<View style={styles.container}>
<Animated.View
style={[styles.rectangle, this.getRectanglePositionStyles()]}
{...this.state.rectanglePanResponder.panHandlers}>
</Animated.View>
<View style={styles.footer}>
<Button title="Reset" onPress={this.resetPosition}></Button>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
borderColor: 'red',
backgroundColor: '#F5FCFF',
},
footer: {
borderWidth: 1,
width: '100%',
position: 'absolute',
bottom: 0,
left: 0,
backgroundColor: 'blue',
},
rectangle: {
position: 'absolute',
height: 50,
width: 50,
backgroundColor: 'red'
}
});
If your only intention is to put it on upper left corner:
resetPosition = () => {
this.state.rectanglePosition.setValue({ x: 0, y: 0 });
};
Note! Refer to this snack to see how you do it without a state https://snack.expo.io/#ziyoshams/stack-overflow

Absolute positioning not working inside FlatList

I am trying to create a tinder like swipe deck animation. I am using FlatList to render the images. To stack the images one above the other, I am using 'absolute' positioning. The issue with this is the images are not getting rendered and all I am seeing is a blank screen. I am not sure whether there is something wrong with using positioning inside FlatList.
The reason I went with FlatList is my stack will contain around 200 to 300 images. I think I can implement this without using FlatList by just rendering the images as batches (say render 10 images at once and then render the next 10 and so on).
I want to know whether it is possible to implement this using FlatList.
NOTE: The issue is in android and I am not sure about iOS
import React from "react";
import {
StyleSheet,
Text,
View,
FlatList,
Image,
Dimensions,
Animated,
PanResponder
} from "react-native";
const DATA = [
{
id: 1,
text: "Card #1",
uri: "http://www.fluxdigital.co/wp-content/uploads/2015/04/Unsplash.jpg"
},
{
id: 2,
text: "Card #2",
uri: "https://images.pexels.com/photos/247932/pexels-photo-247932.jpeg?h=350"
},
{
id: 3,
text: "Card #3",
uri: "http://www.fluxdigital.co/wp-content/uploads/2015/04/Unsplash.jpg"
}
];
const { width, height } = Dimensions.get("window");
export default class App extends React.Component {
constructor(props) {
super(props);
this.position = new Animated.ValueXY();
this.panResponder = PanResponder.create({
onStartShouldSetPanResponder: (event, gestureState) => true,
onPanResponderMove: (event, gestureState) => {},
onPanResponderRelease: (event, gestureState) => {}
});
this.state = {
currentIndex: 0
};
}
extractKey = (item, index) => item.id.toString();
renderCard = ({ item }) => {
return (
<View style={styles.imageContainer}>
<Image
source={{ uri: item.uri }}
resizeMode="cover"
style={styles.image}
/>
</View>
);
};
render() {
return (
<FlatList
contentContainerStle={styles.container}
data={DATA}
keyExtractor={this.extractKey}
renderItem={this.renderCard}
scrollEnabled={true}
/>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1
},
imageContainer: {
width,
height: height - 20,
backgroundColor: "red",
padding: 10
position: 'absolute'
},
image: {
flex: 1,
width: null,
height: null,
borderRadius: 20
}
});
i create tinder swiper using following
might be help you
import React from "react";
import {
StyleSheet,
Text,
View,
FlatList,
Image,
Dimensions,
Animated,
PanResponder
} from "react-native";
const SCREEN_HEIGHT = Dimensions.get('window').height
const SCREEN_WIDTH = Dimensions.get('window').width
const DATA = [
{
id: 1,
text: "Card #1",
uri: "https://images.pexels.com/photos/247932/pexels-photo-247932.jpeg?h=350"
},
{
id: 2,
text: "Card #2",
uri: "http://www.fluxdigital.co/wp-content/uploads/2015/04/Unsplash.jpg"
},
{
id: 3,
text: "Card #3",
uri: "http://www.fluxdigital.co/wp-content/uploads/2015/04/Unsplash.jpg"
}
];
export default class App extends React.Component {
constructor(props) {
super(props);
this.position = new Animated.ValueXY();
this.panResponder = PanResponder.create({
onStartShouldSetPanResponder: (event, gestureState) => true,
onPanResponderMove: (event, gestureState) => {},
onPanResponderRelease: (event, gestureState) => {}
});
this.state = {
currentIndex: 0
};
}
extractKey = (item, index) => item.id.toString();
renderUsers = () => {
return DATA.map((item,i)=>{
return(
<View style={ { height: SCREEN_HEIGHT - 120, width: SCREEN_WIDTH, padding: 10, position: 'absolute' }}>
<Image
style={{ flex: 1, height: null, width: null, resizeMode: 'cover', borderRadius: 20 }}
source={{uri:item.uri}} />
</View>
)
})
}
render() {
return (
<View style={{marginTop:24,flex:1,backgroundColor:'#eee'}}>
{
this.renderUsers()
}
</View>
);
}
}

drag and resize a shape in react-native

im new to react-native and overhelmed with all the options in the www. thats why i'm a bit confused how to complete this task in the best possible way.
i want to make something similar to this, but in react-native. A square-shape, which i can drag all over the view + resize it by dragging it's corners. I already took a look into exponent IDE and the given ThreeView-Component, but i think three.js is a bit over the top for this task, right?
[1]: http://codepen.io/abruzzi/pen/EpqaH
react-native-gesture-handler is the most appropriate thing for your case. I have created minimal example in snack. Here is the minimal code:
let FlatItem = ({ item }) => {
let translateX = new Animated.Value(0);
let translateY = new Animated.Value(0);
let height = new Animated.Value(20);
let onGestureEvent = Animated.event([
{
nativeEvent: {
translationX: translateX,
translationY: translateY,
},
},
]);
let onGestureTopEvent = Animated.event([
{
nativeEvent: {
translationY: height,
},
},
]);
let _lastOffset = { x: 0, y: 0 };
let onHandlerStateChange = event => {
if (event.nativeEvent.oldState === State.ACTIVE) {
_lastOffset.x += event.nativeEvent.translationX;
_lastOffset.y += event.nativeEvent.translationY;
translateX.setOffset(_lastOffset.x);
translateX.setValue(0);
translateY.setOffset(_lastOffset.y);
translateY.setValue(0);
}
};
return (
<View>
<PanGestureHandler onGestureEvent={onGestureTopEvent}>
<Animated.View
style={{
widht: 10,
height,
backgroundColor: 'blue',
transform: [{ translateX }, { translateY }],
}}
/>
</PanGestureHandler>
<PanGestureHandler
onGestureEvent={onGestureEvent}
onHandlerStateChange={onHandlerStateChange}>
<Animated.View
style={[
styles.item,
{ transform: [{ translateX }, { translateY }] },
]}>
<Text>{item.id}</Text>
</Animated.View>
</PanGestureHandler>
</View>
);
};
let data = [
{ key: 1, id: 1 },
];
export default class App extends React.Component {
render() {
return (
<View style={styles.container}>
<FlatItem item={data[0]} />
</View>
);
}
}
Here is the snack link if you want to test! PS: I have made only top resizing. The rest is for you to do! It should be enough to understand the way how to it!

Animated.Image with PanResponder 'react-native

I am using Animated.Image inside a scrollView. I apply a pan responder to the Animated.Image.
The problem: when I move the image for big distance, it disappears.
The question: how can I adjust the Animated.Image to stay within specific boundaries when i move it?
My code:
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
Image,
Animated,
PanResponder,
ScrollView
} from 'react-native';
var xPosition, yPosition;
var position;
export default class AvatarEditor extends Component {
constructor(props) {
super(props);
this.state = {
pan: new Animated.ValueXY(), // inits to zero
image: this.props.image,
border: this.props.border,
width: this.props.width,
height: this.props.height,
viewWidth: this.props.width + 2 * this.props.border,
viewHeight: this.props.height + 2 * this.props.border,
first: true,
left: 0,
top: 0,
xPosition: 0,
yPosition: 0,
translateX: 0,
translateY: 0
};
}
componentWillMount() {
this._animatedValueX = 0;
this._animatedValueY = 0;
this.state.pan.x.addListener((value) => this._animatedValueX = value.value);
this.state.pan.y.addListener((value) => this._animatedValueY = value.value);
this._panResponder = PanResponder.create({
onMoveShouldSetResponderCapture: () => true, //Tell iOS that we are allowing the movement
onMoveShouldSetPanResponderCapture: () => true, // Same here, tell iOS that we allow dragging
onPanResponderGrant: (e, gestureState) => {
this.state.pan.setOffset({ x: this._animatedValueX, y: this._animatedValueY });
this.state.pan.setValue({ x: 0, y: 0 }); //Initial value
},
onPanResponderMove: (evt, gestureState) => {
// Animated.event([
// null, { dx: this.state.pan.x, dy: this.state.pan.y }
// ]) // Creates a function to handle the movement and set offsets
newdx = gestureState.dx;
newdy = gestureState.dy;
Animated.event([
null, { dx: this.state.pan.x, dy: this.state.pan.y },
])(evt, { dx: newdx, dy: newdy });
},
onPanResponderRelease: () => {
this.state.pan.flattenOffset(); // Flatten the offset so it resets the default positioning
}
});
}
componentDidMount() {
}
componentWillUnmount() {
this.state.pan.x.removeAllListeners();
this.state.pan.y.removeAllListeners();
}
render() {
var imageStyle = {
width: this.state.width,
height: this.state.height,
resizeMode: 'stretch',
top: this.state.top,
left: this.state.left,
transform: [
{ translateX: this.state.pan.x },//this.state.pan.x
{ translateY: this.state.pan.y },
{ scale: this.props.scale }
]
};
return (
<View
style={[this.props.style, { backgroundColor: 'gray' }]}
>
<ScrollView
style={{
width: this.state.viewWidth,
height: this.state.viewHeight,
borderWidth: this.state.border,
borderColor: 'rgba(100, 100, 100, 0.5)',
overflow: 'hidden',
}}
scrollEnabled={false}
>
<Animated.Image
style={imageStyle}
source={{ uri: this.state.image }}
{...this._panResponder.panHandlers}
>
</Animated.Image>
</ScrollView>
</View>
);
}
}
AvatarEditor.propTypes = {
scale: React.PropTypes.number,
image: React.PropTypes.string,
border: React.PropTypes.number,
width: React.PropTypes.number,
height: React.PropTypes.number,
style: React.PropTypes.object
};
AvatarEditor.defaultProps = {
scale: 1,
border: 25,
width: 200,
height: 200,
style: {
top: 50,
left: 25,
position: 'absolute',
},
image: 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQesv5ucRQ1KUNtDipnrhS6Gn9yMn7GOqFdQGTeLMG1fCKGvudEUji_Aw',
};