I'm making a short game with react native where one image at a time is moving from top to bottom of the screen using Animated. Now I need the moving image to be draggable so that I can programme the drop part after. I'm already using PanResponder but I still can't drag the image. You can see my code below. Any ideas on how to fix this? Thank you for your attention.
import React from 'react';
import { StyleSheet, Text, View, Image, StatusBar, Dimensions, Animated, TouchableOpacity, PanResponder } from 'react-native';
import { Actions } from 'react-native-router-flux';
const largura = Dimensions.get('window').width;
const altura = Dimensions.get('window').height;
export default class JogoArrasto extends React.Component {
constructor(props) {
super(props);
this.state = {
left: Math.floor(Math.random() * ((largura - 120) - 120)) + 120,
randomImg: Math.floor(Math.random() * (5 - 1)) + 1,
ingCair: null,
maca: require('../imgs/maca.png'),
doce: require('../imgs/doce.png'),
gema: require('../imgs/gema.png'),
corpoDeus: require('../imgs/corpoDeus.png'),
acucar: require('../imgs/acucar.png'),
pan: new Animated.ValueXY(), //Step 1 do drag & drop
ingCertos: 0,
ingErrados: 0
}
this.animatedValue2 = new Animated.Value(0);
this.panResponder = PanResponder.create({ //Step 2 do drag & drop
onStartShouldSetPanResponder: () => true,
onPanResponderMove: Animated.event([null, { //Step 3 do drag & drop
dx: this.state.pan.x,
dy: this.state.pan.y
}]),
onPanResponderRelease: (e, gesture) => { } //Step 4 do drag & drop
});
}
componentDidMount() {
if (this.state.randomImg === 1) {
this.setState({
ingCair: this.state.maca
})
} else if (this.state.randomImg === 2) {
this.setState({
ingCair: this.state.doce
})
} else if (this.state.randomImg === 3) {
this.setState({
ingCair: this.state.gema
})
} else if (this.state.randomImg === 4) {
this.setState({
ingCair: this.state.corpoDeus
})
} else if (this.state.randomImg === 5) {
this.setState({
ingCair: this.state.acucar
})
}
this.moveIng2();
}
moveIng2 = () => {
console.log('ing: ' + this.state.randomImg);
this.animatedValue2.setValue(-120);
Animated.sequence([
Animated.timing(this.animatedValue2, {
toValue: -120,
duration: 1
}),
Animated.timing(this.animatedValue2, {
toValue: 600,
duration: 3000
})
]).start(() => {
this.animatedValue2.addListener(({
value
}) => this._value = value);
let valor = this.animatedValue2._value.toFixed(1);
this.confere(valor);
});
}
confere = (atualValorIng) => {
if (atualValorIng == 600) {
Animated.timing(this.animatedValue2).stop();
const novoRandom = Math.floor(Math.random() * (5 - 1)) + 1;
this.setState({
left: Math.floor(Math.random() * ((largura - 120) - 120)) + 120,
randomImg: novoRandom
})
if (this.state.randomImg === 1) {
this.setState({
ingCair: this.state.maca
})
} else if (this.state.randomImg === 2) {
this.setState({
ingCair: this.state.doce
})
} else if (this.state.randomImg === 3) {
this.setState({
ingCair: this.state.gema
})
} else if (this.state.randomImg === 4) {
this.setState({
ingCair: this.state.corpoDeus
})
} else if (this.state.randomImg === 5) {
this.setState({
ingCair: this.state.acucar
})
}
this.moveIng2();
}
}
render() {
return (
<View style={styles.main}>
<StatusBar hidden />
<TouchableOpacity style={styles.circle} onPress={() => { Actions.menu(); }}>
<Text style={styles.textoMenu}>Menu</Text>
</TouchableOpacity>
<View style={styles.viewImg}>
<Image style={styles.img1} source={require('../imgs/cestoOutros.png')} />
<Image style={styles.img2} source={require('../imgs/tacho.png')} />
</View>
<Animated.Image
{...this.panResponder.panHandlers}
style={[this.state.pan.getLayout(), {
position: 'absolute',
width: 90,
top: this.animatedValue2,
left: this.state.left
}]} source={this.state.ingCair} />
</View>
);
}
}
const styles = StyleSheet.create({
main: {
backgroundColor: '#324C5A',
flex: 1,
width: '100%',
height: '100%',
flexWrap: 'wrap',
alignItems: 'center',
alignContent: 'center',
},
circle: {
width: 160,
height: 80,
justifyContent: 'center',
borderBottomLeftRadius: 180,
borderBottomRightRadius: 180,
backgroundColor: '#fff',
marginBottom: 20
},
textoMenu: {
color: '#1D1D1D',
fontWeight: 'bold',
textAlign: 'center',
fontSize: 18
},
img1: {
display: 'flex',
width: 128,
marginRight: 20
},
img2: {
display: 'flex',
width: 128
},
viewImg: {
flexDirection: 'row',
justifyContent: 'center',
position: 'absolute',
bottom: 10,
alignContent: 'center'
}
})
Update
If I comment these two lines top: this.animatedValue2, left: this.state.left I can drag the Image, but it stops falling from the top to the bottom of the screen. Help please...
I don't get what exactly do you want but after commenting out top: this.animatedValue2 left: this.state.left Your image response to draggable.
<Animated.Image
{...this.panResponder.panHandlers}
style={[this.state.pan.getLayout(), {
position: 'absolute',
width: 90,
height:500,
// top: this.animatedValue2, <--- comment out this line
// left: this.state.left <--- comment out this line
}]}source={this.state.ingCair} />
Not sure exactly what the issue is, but a few bits of advice that'll help:
when I keep animated values in state, sometimes setting state in the middle of an animation makes for weird behavior, so I'd keep it out of state and use a standard animated value.
instead of using top/left (which aren't supported by the native driver), use transform: [{ translateX }, { translateY }] that way you can use the native driver, it'll make the animation way more performant.
check out rn-gesture-handler
Related
as i am new in react native. i have no much knowledge of class component. i was stuck in code as class components are used in this code but i want to convert them into functional components. anyone please help me to convert this given code into functional component. this is a code of a swipeable card in react native all the given code in class component and use of constructor and this. i want to just convert it into functional component.
//This is an example of Tinder like Swipeable Card//
import React, { Component } from 'react';
//import react in our code.
import {
Platform, StyleSheet, View, Text,
Dimensions, Animated, PanResponder,
} from 'react-native';
//import all the components we are going to use.
const SCREEN_WIDTH = Dimensions.get('window').width;
class SwipeableCard extends React.Component {
constructor() {
super();
this.panResponder;
this.state = {
Xposition: new Animated.Value(0),
RightText: false,
LeftText: false,
};
this.Card_Opacity = new Animated.Value(1);
this.panResponder = PanResponder.create({
onStartShouldSetPanResponder: (evt, gestureState) => false,
onMoveShouldSetPanResponder: (evt, gestureState) => true,
onStartShouldSetPanResponderCapture: (evt, gestureState) => false,
onMoveShouldSetPanResponderCapture: (evt, gestureState) => true,
onPanResponderMove: (evt, gestureState) => {
this.state.Xposition.setValue(gestureState.dx);
if (gestureState.dx > SCREEN_WIDTH - 250) {
this.setState({
RightText: true,
LeftText: false,
});
} else if (gestureState.dx < -SCREEN_WIDTH + 250) {
this.setState({
LeftText: true,
RightText: false,
});
}
},
onPanResponderRelease: (evt, gestureState) => {
if (
gestureState.dx < SCREEN_WIDTH - 150 &&
gestureState.dx > -SCREEN_WIDTH + 150
) {
this.setState({
LeftText: false,
RightText: false,
});
Animated.spring(
this.state.Xposition,
{
toValue: 0,
speed: 5,
bounciness: 10,
},
{ useNativeDriver: true }
).start();
} else if (gestureState.dx > SCREEN_WIDTH - 150) {
Animated.parallel(
[
Animated.timing(this.state.Xposition, {
toValue: SCREEN_WIDTH,
duration: 200,
}),
Animated.timing(this.Card_Opacity, {
toValue: 0,
duration: 200,
}),
],
{ useNativeDriver: true }
).start(() => {
this.setState({ LeftText: false, RightText: false }, () => {
this.props.removeCard();
});
});
} else if (gestureState.dx < -SCREEN_WIDTH + 150) {
Animated.parallel(
[
Animated.timing(this.state.Xposition, {
toValue: -SCREEN_WIDTH,
duration: 200,
}),
Animated.timing(this.Card_Opacity, {
toValue: 0,
duration: 200,
}),
],
{ useNativeDriver: true }
).start(() => {
this.setState({ LeftText: false, RightText: false }, () => {
this.props.removeCard();
});
});
}
},
});
}
render() {
const rotateCard = this.state.Xposition.interpolate({
inputRange: [-200, 0, 200],
outputRange: ['-20deg', '0deg', '20deg'],
});
return (
<Animated.View
{...this.panResponder.panHandlers}
style={[
styles.card_Style,
{
backgroundColor: this.props.item.backgroundColor,
opacity: this.Card_Opacity,
transform: [
{ translateX: this.state.Xposition },
{ rotate: rotateCard },
],
},
]}>
<Text style={styles.Card_Title}> {this.props.item.card_Title} </Text>
{this.state.LeftText ? (
<Text style={styles.Left_Text_Style}> Left Swipe </Text>
) : null}
{this.state.RightText ? (
<Text style={styles.Right_Text_Style}> Right Swipe </Text>
) : null}
</Animated.View>
);
}
}
export default class App extends React.Component {
constructor() {
super();
this.state = {
Sample_Card_Array: [{
id: '1', card_Title: 'Card 1', backgroundColor: '#FFC107',
}, {
id: '2', card_Title: 'Card 2', backgroundColor: '#ED2525',
}, {
id: '3', card_Title: 'Card 3', backgroundColor: '#E7088E',
}, {
id: '4', card_Title: 'Card 4', backgroundColor: '#00BCD4',
}, {
id: '5', card_Title: 'Card 5', backgroundColor: '#FFFB14',
}],
No_More_Card: false,
};
}
componentDidMount() {
this.setState({
Sample_Card_Array: this.state.Sample_Card_Array.reverse(),
});
if (this.state.Sample_Card_Array.length == 0) {
this.setState({ No_More_Card: true });
}
}
removeCard = id => {
this.state.Sample_Card_Array.splice(
this.state.Sample_Card_Array.findIndex(x => x.id == id),
1
);
this.setState({ Sample_Card_Array: this.state.Sample_Card_Array }, () => {
if (this.state.Sample_Card_Array.length == 0) {
this.setState({ No_More_Card: true });
}
});
};
render() {
return (
<View style={styles.MainContainer}>
{this.state.Sample_Card_Array.map((item, key) => (
<SwipeableCard
key={key}
item={item}
removeCard={this.removeCard.bind(this, item.id)}
/>
))}
{this.state.No_More_Card ? (
<Text style={{ fontSize: 22, color: '#000' }}>No Cards Found.</Text>
) : null}
</View>
);
}
}
const styles = StyleSheet.create({
MainContainer: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
paddingTop: Platform.OS === 'ios' ? 20 : 0,
},
card_Style: {
width: '75%',
height: '45%',
justifyContent: 'center',
alignItems: 'center',
position: 'absolute',
borderRadius: 7,
},
Card_Title: {
color: '#fff',
fontSize: 24,
},
Left_Text_Style: {
top: 22,
right: 32,
position: 'absolute',
color: '#fff',
fontSize: 20,
fontWeight: 'bold',
backgroundColor: 'transparent',
},
Right_Text_Style: {
top: 22,
left: 32,
position: 'absolute',
color: '#fff',
fontSize: 20,
fontWeight: 'bold',
backgroundColor: 'transparent',
},
});
the part in the render method is what you return.
to create stateObjects in functional components you will need to use the useState method
const functionalComponent = (props)=>{//props are passed in via props arg...
const defaultState = Xposition: new Animated.Value(0),
RightText: false,
LeftText: false
}
const [state,setState] = useState(defaultState);
... // more stuff
return (
<Animated.View
{...this.panResponder.panHandlers}
style={[
styles.card_Style,
{
backgroundColor: props.item.backgroundColor,
opacity: Card_Opacity,
transform: [
{ translateX: state.Xposition },
{ rotate: rotateCard },
],
},
]}>
<Text style={styles.Card_Title}> {props.item.card_Title} </Text>
{this.state.LeftText ? (
<Text style={styles.Left_Text_Style}> Left Swipe </Text>
) : null}
{this.state.RightText ? (
<Text style={styles.Right_Text_Style}> Right Swipe </Text>
) : null}
</Animated.View>
);
}
you should really go watch some videos on useState, you can be much more granular
to set the state you will need to use the setState method returned from the useState call : setState({..state,{XPosition:55}) or something ... you do the ...state to include the old state values, as the state variable will be overwritten with exactly what you pass in... it wont "update" the existing state it will overwrite it
the next bit is hooking into the functionality in componentDidMount you can do this with useEffect
useEffect(()=>{ // this is setup
// do the stuff from componentDidMount
return ()=>{
// any required teardown can be done here
},[] //[] signifies only do this when component mounts... not every update
);// end useEffect componentDidMount
again there is alot more to useEffect, if you want to do stuff when specific state or props are updated
Hey everyone :) Should be a function for a navigation avatar which sticks to the closest corner. While coding I used a simple circle as a placeholder. The problem is that the following code works perfectly fine when imported to another screen, but when I replace <View style={styles.circle} /> with an image <Image source={require("../assets/dude.png")} resizeMode="contain" style={{width: 180, height: 240,}}/> it doesnt work anymore? Like I can see the image, but the animations work extremely buggy and it just goes anywhere, nothing like it's supposed to do?
I tried it also with Animated.Image instead of the view and giving it all the parameters, still no change. The weird thing is that the Image works perfectly fine if I were to run this code as a screen itself, but when I import it only the circle view works, not the image?
EDIT: Just found the issue: if the Animated.Image is in front of a Scrollable View, even if it isn't part of that View, it bugs. If I replace the image with anything else (like a Box), it works fine, only the image bugs in that manner :) which leads me to my next question: How can I fix that?
so this is my code:
import React from "react";
import {
StyleSheet,
View,
Dimensions,
Animated,
PanResponder,
Image,
} from "react-native";
export default class Avatar extends React.Component {
constructor(props) {
super(props);
this.state = {
pan: new Animated.ValueXY(),
screenMeasurements: {
width: Screen.width / 2,
height: Screen.height / 2,
},
};
this.panResponder = PanResponder.create({
onStartShouldSetPanResponder: () => true,
onPanResponderGrant: () => {
this.state.pan.setOffset({
x: this.state.pan.x._value,
y: this.state.pan.y._value,
});
},
onPanResponderMove: Animated.event([
null,
{
dx: this.state.pan.x,
dy: this.state.pan.y,
},
]),
onPanResponderRelease: (e, gesture) => {
if (this.whichField(gesture) == 1) {
console.log("top left");
this.state.pan.flattenOffset();
Animated.spring(this.state.pan, {
toValue: {
x: (Screen.width * 0.5 - 90) * -1,
y: (Screen.height * 0.5 - 120) * -1,
},
}).start();
} else if (this.whichField(gesture) == 2) {
console.log("top right");
this.state.pan.flattenOffset();
Animated.spring(this.state.pan, {
toValue: {
x: Screen.width * 0.5 - 90,
y: (Screen.height * 0.5 - 120) * -1,
},
}).start();
} else if (this.whichField(gesture) == 3) {
console.log("bottom left");
this.state.pan.flattenOffset();
Animated.spring(this.state.pan, {
toValue: {
x: (Screen.width * 0.5 - 90) * -1,
y: Screen.height * 0.5 - 150,
},
}).start();
} else {
console.log("bottom right");
this.state.pan.flattenOffset();
Animated.spring(this.state.pan, {
toValue: {
x: Screen.width * 0.5 - 90,
y: Screen.height * 0.5 - 150,
},
}).start();
}
},
});
}
whichField(gesture) {
var sm = this.state.screenMeasurements;
let field;
{
gesture.moveY < sm.height && gesture.moveX < sm.width
? (field = 1)
: gesture.moveY < sm.height && gesture.moveX > sm.width
? (field = 2)
: gesture.moveY > sm.height && gesture.moveX < sm.width
? (field = 3)
: (field = 4);
}
return field;
}
render() {
return (
<View style={styles.draggableContainer}>
<Animated.View
style={[this.state.pan.getLayout()]}
{...this.panResponder.panHandlers}
>
<View style={styles.circle} />
</Animated.View>
</View>
);
}
}
let Screen = Dimensions.get("screen");
let CIRCLE_RADIUS = 45;
const styles = StyleSheet.create({
text: {
marginTop: 25,
marginLeft: 5,
marginRight: 5,
textAlign: "center",
color: "#fff",
},
draggableContainer: {
position: "absolute",
top: Screen.height / 2 - CIRCLE_RADIUS,
left: Screen.width / 2 - CIRCLE_RADIUS,
},
circle: {
backgroundColor: "#1abc9c",
width: CIRCLE_RADIUS * 2,
height: CIRCLE_RADIUS * 2,
borderRadius: CIRCLE_RADIUS,
},
});
Check out this similar animation of badge Above ScrollView.
You need to place the Image inside an Animated View.
Example code:
import React, {Component} from 'react';
import {
StyleSheet,
View,
PanResponder,
Animated,
Dimensions,
ScrollView,
Image,
} from 'react-native';
const {height, width} = Dimensions.get('screen');
export default class SampleApp extends Component {
constructor() {
super();
this._animatedValue = new Animated.ValueXY({x: 20, y: 20});
this._value = {x: 20, y: 20};
this._animatedValue.addListener((value) => (this._value = value));
this._panResponder = PanResponder.create({
onMoveShouldSetResponderCapture: () => true,
onMoveShouldSetPanResponderCapture: () => true,
onPanResponderGrant: (e, gestureState) => {
this._animatedValue.setOffset({x: this._value.x, y: this._value.y});
this._animatedValue.setValue({x: 0, y: 0});
},
onPanResponderMove: Animated.event([
null,
{dx: this._animatedValue.x, dy: this._animatedValue.y},
]),
onPanResponderRelease: (e, gesture) => {
this._animatedValue.flattenOffset();
if (this.whichField(gesture) == 1) {
Animated.spring(this._animatedValue, {
toValue: {x: 20, y: 20},
}).start();
} else if (this.whichField(gesture) == 2) {
Animated.spring(this._animatedValue, {
toValue: {x: width - 120, y: 20},
}).start();
} else if (this.whichField(gesture) == 3) {
Animated.spring(this._animatedValue, {
toValue: {x: 20, y: height - 150},
}).start();
} else {
Animated.spring(this._animatedValue, {
toValue: {x: width - 120, y: height - 150},
}).start();
}
},
});
}
whichField(gesture) {
var sm = {height, width};
let field;
{
gesture.moveY < sm.height / 2 && gesture.moveX < sm.width / 2
? (field = 1)
: gesture.moveY < sm.height / 2 && gesture.moveX > sm.width / 2
? (field = 2)
: gesture.moveY > sm.height / 2 && gesture.moveX < sm.width / 2
? (field = 3)
: (field = 4);
}
return field;
}
render() {
return (
<View style={styles.container}>
<ScrollView>
{['', '', '', '', '', ''].map(() => (
<View style={styles.scrollItem} />
))}
</ScrollView>
<Animated.View
style={[
styles.box,
{
transform: [
{translateX: this._animatedValue.x},
{translateY: this._animatedValue.y},
],
},
]}
{...this._panResponder.panHandlers}>
<Image
source={{
uri:
'https://pluspng.com/img-png/user-png-icon-male-user-icon-512.png',
}}
style={StyleSheet.absoluteFill}
/>
</Animated.View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
box: {
width: 100,
height: 100,
borderRadius: 50,
backgroundColor: '#fff',
position: 'absolute',
},
scrollItem: {
height: 300,
width: '100%',
backgroundColor: 'grey',
marginBottom: 10,
},
});
Check in Expo
I hope it will help you.
Description
I am working on a react-native project using expo SDK36.
I want to do a swipe left/right list view. I use react-native-swipe-list-view to achieve it.
So far everything worked perfectly, the default example uses a fixed height: 50 per row, while I want to set the height of each row dynamically.
Every attempt where a failure, note that I already use <SwipeListView recalculateHiddenLayout={true} />
This is bad for the UX, since the default line is having a small height: 50, it is nearly impossible to drag the line on iOS and android properly.
Reproduction
Snack: https://snack.expo.io/#kopax/react-native-swipe-list-view-408
import React from 'react';
import { Dimensions, Text, View, StyleSheet } from 'react-native';
import Constants from 'expo-constants';
// You can import from local files
import SwipeListView from './components/SwipeListView';
// or any pure javascript modules available in npm
import { Card } from 'react-native-paper';
export default class App extends React.Component {
render() {
return (
<View style={styles.container}>
<Text style={styles.paragraph}>
Change code in the editor and watch it change on your phone! Save to get a shareable url.
</Text>
<Card>
<SwipeListView
dimensions={Dimensions.get('window')}
listViewData={Array(20).fill('').map((d, i) => ({
...d,
title: `Item ${i}`,
description: `This is a very long description for item number #${i},
it should be so long that you cannot see all the content,
the issue is about fixing the dynamic height for each row`
}))
}
minHeight={200}
/>
</Card>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
paddingTop: Constants.statusBarHeight,
backgroundColor: '#ecf0f1',
padding: 8,
},
paragraph: {
margin: 24,
fontSize: 18,
fontWeight: 'bold',
textAlign: 'center',
},
});
This is my components/SwipeListView.js
import React, { Component } from 'react';
import {
Animated,
Image,
StyleSheet,
TouchableOpacity,
TouchableHighlight,
View,
} from 'react-native';
import {
Avatar,
Button,
Text,
Title,
Subheading,
TouchableRipple,
withTheme,
} from 'react-native-paper';
import { SwipeListView as SwipeListViewDefault } from 'react-native-swipe-list-view';
/* eslint-disable react/prop-types, react/destructuring-assignment, react/no-access-state-in-setstate */
class SwipeListView extends Component {
leftBtnRatio = 0.25;
rightBtnRatio = 0.75;
constructor(props) {
super(props);
this.state = {
listType: 'FlatList',
listViewData: props.listViewData
.map((data, i) => ({ key: `${i}`, ...data })),
};
this.rowTranslateAnimatedValues = {};
props.listViewData
.forEach((data, i) => {
this.rowTranslateAnimatedValues[`${i}`] = new Animated.Value(1);
});
}
getStyles() {
const { minHeight, theme } = this.props;
const { colors } = theme;
return StyleSheet.create({
rowFrontContainer: {
overflow: 'hidden',
},
rowFront: {
alignItems: 'center',
backgroundColor: colors.surface,
borderBottomColor: colors.accent,
borderBottomWidth: 1,
justifyContent: 'center',
minHeight: '100%',
flex: 1,
},
rowBack: {
alignItems: 'center',
backgroundColor: colors.surface,
flexDirection: 'row',
justifyContent: 'space-between',
paddingLeft: 15,
minHeight: '100%',
},
backBtn: {
alignItems: 'center',
bottom: 0,
justifyContent: 'center',
position: 'absolute',
top: 0,
},
backLeftBtn: {
backgroundColor: colors.primary,
left: 0,
width: `${this.leftBtnRatio * 100}%`,
},
backRightBtn: {
backgroundColor: colors.accent,
right: 0,
width: `${this.rightBtnRatio * 100}%`,
},
});
}
onRowDidOpen = (rowKey) => {
console.log('This row opened', rowKey);
};
onSwipeValueChange = swipeData => {
const { dimensions } = this.props;
const { key, value } = swipeData;
if (value < -dimensions.width * this.rightBtnRatio && !this.animationIsRunning) {
this.animationIsRunning = true;
Animated.timing(this.rowTranslateAnimatedValues[key], {
toValue: 0,
duration: 200,
}).start(() => {
const newData = [...this.state.listViewData];
const prevIndex = this.state.listViewData.findIndex(item => item.key === key);
newData.splice(prevIndex, 1);
this.setState({listViewData: newData});
this.animationIsRunning = false;
});
}
};
closeRow(rowMap, rowKey) {
if (rowMap[rowKey]) {
rowMap[rowKey].closeRow();
}
}
deleteRow(rowMap, rowKey) {
this.closeRow(rowMap, rowKey);
const newData = [...this.state.listViewData];
const prevIndex = this.state.listViewData.findIndex(
(item) => item.key === rowKey,
);
newData.splice(prevIndex, 1);
this.setState({ listViewData: newData });
}
render() {
const { minHeight, dimensions, theme } = this.props;
const { colors } = theme;
const styles = this.getStyles();
return (
<SwipeListViewDefault
data={this.state.listViewData}
renderItem={data => (
<Animated.View
style={[styles.rowFrontContainer, {
height: this.rowTranslateAnimatedValues[data.item.key].interpolate({
inputRange: [0, 1],
outputRange: [0, minHeight],
})}]}
>
<TouchableRipple
onPress={() => console.log('You touched me')}
style={styles.rowFront}
underlayColor={colors.background}
>
<View>
<Title>{data.item.title}</Title>
<Text>
{data.item.description}
</Text>
</View>
</TouchableRipple>
</Animated.View>
)}
renderHiddenItem={(data, rowMap) => (
<View style={styles.rowBack}>
<TouchableOpacity
style={[
styles.backLeftBtn,
styles.backBtn,
]}
onPress={() => this.closeRow(rowMap, data.item.key)}
>
<Text>Tap pour annuler</Text>
</TouchableOpacity>
<TouchableOpacity
style={[
styles.backRightBtn,
styles.backBtn,
]}
onPress={() => this.deleteRow(rowMap, data.item.key)}
>
<Animated.View
style={[
styles.trash,
{
transform: [
{
scale: this.rowTranslateAnimatedValues[
data.item.key
].interpolate({
inputRange: [
45,
90,
],
outputRange: [0, 1],
extrapolate:
'clamp',
}),
},
],
},
]}
>
<Text>Swipe left to delete</Text>
</Animated.View>
</TouchableOpacity>
</View>
)}
leftOpenValue={dimensions.width * this.leftBtnRatio}
rightOpenValue={-dimensions.width * this.rightBtnRatio}
previewRowKey={'0'}
previewOpenValue={-40}
previewOpenDelay={3000}
onRowDidOpen={this.onRowDidOpen}
onSwipeValueChange={this.onSwipeValueChange}
recalculateHiddenLayout={true}
/>
);
}
}
export default withTheme(SwipeListView);
Expect
I expect when using recalculateHiddenLayout={true}, to get the hidden row height calculated dynamically
Result Screenshots
On the web, I am able to set the height:
but I when using iOS and Android, the height is forced.
Environment
OS: ios/android/web
RN Version: expo SDK36
How can I set the height of each row dynamically?
Important edit
The problem is the fixed value here in the animation:
height: this.rowTranslateAnimatedValues[data.item.key].interpolate({
inputRange: [0, 1],
outputRange: [0, 200], // <--- here
})}]}
I have replaced it in the example with props.minHeight:
height: this.rowTranslateAnimatedValues[data.item.key].interpolate({
inputRange: [0, 1],
outputRange: [0, this.props.minHeight],
})}]}
It doesn't permit dynamic height, how can I get the row height dynamically?
I need to pass the details of the currently active slide to another js file. how can I do this (there are 8 slides)?
The details that I need to pass is the slide's name and Index,
Here is my carousel js file :
import React, { Component } from 'react';
import { Dimensions, View, Image } from 'react-native';
import Carousel from 'react-native-snap-carousel';
const { height, width } = Dimensions.get('window');
class TeamScroll extends Component {
render() {
return (
<View >
<View style={{ transform: [{ rotate: '-14deg' }] }}>
<Carousel
ref={(c) => { this.props.carouselRef = c; }}
inactiveSlideOpacity={0.6}
inactiveSlideScale={0.65}
firstItem={1}
sliderWidth={width}
itemWidth={width / 3} >
<Image
source={require('./Images/logo-chepauk.png')}
style={styles.logoStyle} />
<Image
source={require('./Images/logo-dindigul.png')}
style={styles.logoStyle} />
<Image
source={require('./Images/logo-kanchi.png')}
style={styles.logoStyle} />
<Image
source={require('./Images/logo-karaikudi.png')}
style={styles.logoStyle} />
<Image
source={require('./Images/logo-kovai.png')}
style={styles.logoStyle} />
<Image
source={require('./Images/logomadurai.png')}
style={styles.logoStyle} />
<Image
source={require('./Images/logothiruvallur.png')}
style={styles.logoStyle} />
<Image
source={require('./Images/logotuti.png')}
style={styles.logoStyle} />
</Carousel>
</View>
</View>
);
}
}
const styles = {
logoStyle: {
transform: [{ rotate: '14deg' }],
width: width / 3,
height: width / 3
}
};
export default TeamScroll;
Here is one of the files where I need to use these details
import React, { Component } from 'react';
import { Image, Text, View, TouchableWithoutFeedback, Animated, Dimensions } from 'react-native';
import { Actions } from 'react-native-router-flux';
import TeamScroll from './TeamScroll';
const a = require('./Images/over3_selected.png');
const b = require('./Images/over3.png');
const c = require('./Images/over5_selected.png');
const d = require('./Images/over5.png');
const e = require('./Images/over10_selected.png');
const f = require('./Images/over10.png');
const Sound = require('react-native-sound');
const btnSound = new Sound('btn_sound.mp3', Sound.MAIN_BUNDLE);
const w = Dimensions.get('window').width;
const h = Dimensions.get('window').height;
class ChallengeScreen extends Component {
state = {
threePressed: false,
fivePressed: false,
tenPressed: false,
}
componentWillMount() {
this.slide1 = new Animated.Value(0);
this.slide2 = new Animated.Value(0);
this.slide3 = new Animated.Value(0);
this.ball1();
this.ball2();
this.ball3();
}
ball1() {
Animated.timing(
this.slide1, {
delay: 100,
toValue: -(w / 2.57),
duration: 700,
}
).start();
}
ball2() {
Animated.timing(
this.slide2, {
delay: 200,
toValue: -(w / 2.25),
duration: 900,
}
).start();
}
ball3() {
Animated.timing(
this.slide3, {
delay: 300,
toValue: -(w / 2),
duration: 1100,
}
).start();
}
render() {
return (
<Image
source={require('./Images/bg_inner.png')} style={styles.backgroundStyle}>
<Text style={styles.chooseteamtextStyle}>
CHOOSE YOUR TEAM
</Text>
<Image source={require('./Images/team-logo-band.png')} style={styles.band1Style}>
<TeamScroll carouselRef />
</Image>
<Text style={styles.opponentStyle}>
YOUR OPPONENT
</Text>
<Image source={require('./Images/team-logo-band.png')} style={styles.band2Style}>
<TeamScroll carouselRef />
</Image>
<Text style={styles.overstextStyle}>
OVERS
</Text>
<View style={styles.viewStyle}>
<TouchableWithoutFeedback
onPress={() => {
btnSound.play();
playFunc(3, this.props.challenge); }
}
onPressIn={() => {
this.setState({ threePressed: true });
}}
onPressOut={() => {
this.setState({ threePressed: false });
}}
>
<Animated.Image source={this.state.threePressed ? a : b}
style={[styles.over3Style, { transform: [{ translateY: this.slide1 }] }]} />
</ TouchableWithoutFeedback>
<TouchableWithoutFeedback
onPress={() => {
btnSound.play();
playFunc(5, this.props.challenge); }
}
onPressIn={() => {
this.setState({ fivePressed: true });
}}
onPressOut={() => {
this.setState({ fivePressed: false });
}}>
<Animated.Image source={this.state.fivePressed ? c : d}
style={[styles.over5Style, { transform: [{ translateY: this.slide2 }] }]} />
</ TouchableWithoutFeedback>
<TouchableWithoutFeedback
onPress={() => {
btnSound.play();
playFunc(10, this.props.challenge); }
}
onPressIn={() => {
this.setState({ tenPressed: true });
}}
onPressOut={() => {
this.setState({ tenPressed: false });
}}>
<Animated.Image source={this.state.tenPressed ? e : f}
style={[styles.over10Style, { transform: [{ translateY: this.slide3 }] }]} />
</ TouchableWithoutFeedback>
</View>
</ Image>
);
}
}
function playFunc(num, param) {
if (num === 3 && param === 'Computer') {
Actions.screen4({ balls: 18 });
}
else if (num === 5 && param === 'Computer') {
Actions.screen4({ balls: 30 });
}
else if (num === 10 && param === 'Computer') {
Actions.screen4({ balls: 60 });
}
else if (num === 3 && param === 'Team') {
Actions.screen3({ balls: 18 });
}
else if (num === 5 && param === 'Team') {
Actions.screen3({ balls: 30 });
}
else if (num === 10 && param === 'Team') {
Actions.screen3({ balls: 60 });
}
}
const styles = {
viewStyle: {
flexDirection: 'row',
justifyContent: 'flex-start'
},
backgroundStyle: {
flex: 1,
width: w,
height: h,
flexWrap: 'wrap',
},
chooseteamtextStyle: {
textAlign: 'center',
marginTop: h / 6.57,
fontSize: 22,
color: 'white',
fontFamily: 'Switzerland-Cond-Black-Italic',
transform: [{ rotate: '-14deg' }]
},
band1Style: {
resizeMode: 'stretch',
width: (w / 0.947),
height: (h / 3.93),
},
opponentStyle: {
textAlign: 'center',
marginTop: -(h / 59.2),
fontSize: 22,
color: 'white',
fontFamily: 'Switzerland-Cond-Black-Italic',
transform: [{ rotate: '-15deg' }]
},
band2Style: {
resizeMode: 'stretch',
width: (w / 0.947),
height: (h / 4),
},
overstextStyle: {
textAlign: 'center',
bottom: (h / 59.2),
fontSize: 22,
color: 'white',
fontFamily: 'Switzerland-Cond-Black-Italic',
transform: [{ rotate: '-15deg' }]
},
over3Style: {
flexDirection: 'row',
alignItems: 'flex-start',
width: (w / 4.5),
height: (h / 7.4),
top: (h / 3.482),
left: (w / 5.142),
},
over5Style: {
flexDirection: 'row',
alignItems: 'center',
width: (w / 4.5),
height: (h / 7.4),
bottom: -(h / 3.48),
left: (h / 8.45)
},
over10Style: {
flexDirection: 'row',
alignItems: 'flex-end',
width: (w / 4.5),
height: (h / 7.4),
top: (h / 3.48),
right: -(w / 5.42)
}
};
export default ChallengeScreen;
I have tried using state and props for doing it, and also using getters like currentIndex using carousel's reference but couldn't get the details
What about adding a dedicated prop to <TeamScroll />?
TeamScroll.js
class TeamScroll extends Component {
static propTypes = {
snapCallback: PropTypes.func
}
static defaultProps = {
snapCallback: () => {}
}
constructor (props) {
super(props);
this._onSnapToItem = this._onSnapToItem.bind(this);
}
_onSnapToItem (index) {
this.props.snapCallback(index, this.state.customData);
}
render() {
return (
<View >
<View style={{ transform: [{ rotate: '-14deg' }] }}>
<Carousel onSnapToItem={this._onSnapToItem}>
// images
</Carousel>
</View>
</View>
);
}
}
ChallengeScreen.js
class ChallengeScreen extends Component {
onSnap (index, data) {
console.log('CAROUSEL INDEX', { index, data });
}
render() {
return (
<Image source={require('./Images/team-logo-band.png')} style={styles.band2Style}>
<TeamScroll carouselRef snapCallback={onSnap} />
</Image>
);
}
}
I'm using this
class TeamScroll extends Component {
constructor(props) {
super(props);
this.state = {
currentIndex: 0,
};
}
changePage(nextIndex, isLast) {
this.setState({ currentIndex: nextIndex });
this.props.onChangePage(nextIndex + 1, isLast);
}
render() {
return (
<Page>
<Carousel
ref={(carousel) => { this.carousel = carousel; }}
firstItem={this.state.currentIndex}
onSnapToItem={(index) => this.changePage(index, index === screens.length - 1)}
data={screens}
renderItem={this.renderCarouselItem}
/>
);
}
}
Note that I'm using the new syntax introduced in version 3, but it works as well in version 2.
The class has onChangePage prop that gets called when you snap to another item.
You can use the onChangePage with
<TeamScroll onChangePage={(pageIndex, isLastPage) => {
// do something here, maybe
this.setState({ currentPage: pageIndex });
}} />
I have the following code for my index.io.js file. I am new to react native and don't quite know how to port it to index.android.js. Is there a certain standard that I can follow to migrate this to the android version? What needs to be done exactly?
'use strict';
var ShakeEvent = require('react-native-shake-event-ios');
var NetworkImage = require('react-native-image-progress');
var Progress = require('react-native-progress');
var Swiper = require('react-native-swiper');
var RandManager = require('./RandManager.js');
var Utils = require('./Utils.js');
var React = require('react-native');
// Components
var ProgressHUD = require('./ProgressHUD.js');
var {
AppRegistry,
StyleSheet,
Text,
View,
Component,
ActivityIndicatorIOS,
Dimensions,
PanResponder,
CameraRoll,
AlertIOS
} = React;
var {width, height} = Dimensions.get('window');
const NUM_WALLPAPERS = 5;
const DOUBLE_TAP_DELAY = 300; // milliseconds
const DOUBLE_TAP_RADIUS = 20;
class SplashWalls extends Component{
constructor(props) {
super(props);
this.state = {
wallsJSON: [],
isLoading: true,
isHudVisible: false
};
this.imagePanResponder = {};
// Previous touch information
this.prevTouchInfo = {
prevTouchX: 0,
prevTouchY: 0,
prevTouchTimeStamp: 0
};
this.currentWallIndex = 0;
// Binding this to methods
this.handlePanResponderGrant = this.handlePanResponderGrant.bind(this);
this.onMomentumScrollEnd = this.onMomentumScrollEnd.bind(this);
}
componentDidMount() {
this.fetchWallsJSON();
}
componentWillMount() {
this.imagePanResponder = PanResponder.create({
onStartShouldSetPanResponder: this.handleStartShouldSetPanResponder,
onPanResponderGrant: this.handlePanResponderGrant,
onPanResponderRelease: this.handlePanResponderEnd,
onPanResponderTerminate: this.handlePanResponderEnd
});
// Fetch new wallpapers on shake
ShakeEvent.addEventListener('shake', () => {
this.initialize();
this.fetchWallsJSON();
});
}
render() {
var {isLoading} = this.state;
if(isLoading)
return this.renderLoadingMessage();
else
return this.renderResults();
}
initialize() {
this.setState({
wallsJSON: [],
isLoading: true,
isHudVisible: false
});
this.currentWallIndex = 0;
}
fetchWallsJSON() {
var url = 'http://unsplash.it/list';
fetch(url)
.then( response => response.json() )
.then( jsonData => {
var randomIds = RandManager.uniqueRandomNumbers(NUM_WALLPAPERS, 0, jsonData.length);
var walls = [];
randomIds.forEach(randomId => {
walls.push(jsonData[randomId]);
});
this.setState({
isLoading: false,
wallsJSON: [].concat(walls)
});
})
.catch( error => console.log('JSON Fetch error : ' + error) );
}
renderLoadingMessage() {
return (
<View style={styles.loadingContainer}>
<ActivityIndicatorIOS
animating={true}
color={'#fff'}
size={'small'}
style={{margin: 15}} />
<Text style={{color: '#fff'}}>Contacting Unsplash</Text>
</View>
);
}
saveCurrentWallpaperToCameraRoll() {
// Make Progress HUD visible
this.setState({isHudVisible: true});
var {wallsJSON} = this.state;
var currentWall = wallsJSON[this.currentWallIndex];
var currentWallURL = `http://unsplash.it/${currentWall.width}/${currentWall.height}?image=${currentWall.id}`;
CameraRoll.saveImageWithTag(currentWallURL, (data) => {
// Hide Progress HUD
this.setState({isHudVisible: false});
AlertIOS.alert(
'Saved',
'Wallpaper successfully saved to Camera Roll',
[
{text: 'High 5!', onPress: () => console.log('OK Pressed!')}
]
);
},(err) =>{
console.log('Error saving to camera roll', err);
});
}
onMomentumScrollEnd(e, state, context) {
this.currentWallIndex = state.index;
}
renderResults() {
var {wallsJSON, isHudVisible} = this.state;
return (
<View>
<Swiper
dot={<View style={{backgroundColor:'rgba(255,255,255,.4)', width: 8, height: 8,borderRadius: 10, marginLeft: 3, marginRight: 3, marginTop: 3, marginBottom: 3,}} />}
activeDot={<View style={{backgroundColor: '#fff', width: 13, height: 13, borderRadius: 7, marginLeft: 7, marginRight: 7}} />}
onMomentumScrollEnd={this.onMomentumScrollEnd}
index={this.currentWallIndex}
loop={false}>
{wallsJSON.map((wallpaper, index) => {
return(
<View key={wallpaper.id}>
<NetworkImage
source={{uri: `https://unsplash.it/${wallpaper.width}/${wallpaper.height}?image=${wallpaper.id}`}}
indicator={Progress.Circle}
indicatorProps={{
color: 'rgba(255, 255, 255)',
size: 60,
thickness: 7
}}
threshold={0}
style={styles.wallpaperImage}
{...this.imagePanResponder.panHandlers}>
<Text style={styles.label}>Photo by</Text>
<Text style={styles.label_authorName}>{wallpaper.author}</Text>
</NetworkImage>
</View>
);
})}
</Swiper>
<ProgressHUD width={width} height={height} isVisible={isHudVisible}/>
</View>
);
}
// Pan Handler methods
handleStartShouldSetPanResponder(e, gestureState){
return true;
}
handlePanResponderGrant(e, gestureState) {
var currentTouchTimeStamp = Date.now();
if( this.isDoubleTap(currentTouchTimeStamp, gestureState) )
this.saveCurrentWallpaperToCameraRoll();
this.prevTouchInfo = {
prevTouchX: gestureState.x0,
prevTouchY: gestureState.y0,
prevTouchTimeStamp: currentTouchTimeStamp
};
}
handlePanResponderEnd(e, gestureState) {
// When finger is pulled up from the screen
}
isDoubleTap(currentTouchTimeStamp, {x0, y0}) {
var {prevTouchX, prevTouchY, prevTouchTimeStamp} = this.prevTouchInfo;
var dt = currentTouchTimeStamp - prevTouchTimeStamp;
return (dt < DOUBLE_TAP_DELAY && Utils.distance(prevTouchX, prevTouchY, x0, y0) < DOUBLE_TAP_RADIUS);
}
};
var styles = StyleSheet.create({
loadingContainer: {
flexDirection: 'row',
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#000'
},
wallpaperImage: {
flex: 1,
width: width,
height: height,
backgroundColor: '#000'
},
label: {
position: 'absolute',
color: '#fff',
fontSize: 13,
backgroundColor: 'rgba(0, 0, 0, 0.8)',
padding: 2,
paddingLeft: 5,
top: 20,
left: 20,
width: width/2
},
label_authorName: {
position: 'absolute',
color: '#fff',
fontSize: 15,
backgroundColor: 'rgba(0, 0, 0, 0.8)',
padding: 2,
paddingLeft: 5,
top: 41,
left: 20,
fontWeight: 'bold',
width: width/2
}
});
AppRegistry.registerComponent('SplashWalls', () => SplashWalls);
Copy content of index.ios.js to index.android.js first. If it does not contain any iOS specific code/libs, it will just work. If not, go to step 2.
Adjust code to use Android specific code, or lib API - if such code exists. If not, go to step 3.
Either swap iOS code/libs for Android ones, or write required code yourself.