How to make swipe function on listview (react-native)? - javascript

I have list of items. I am using ListView for it and I need to be able to delete any row by swiping left or right.
Where can I start from here?

If you prefer, follow this guide which uses React Native Swipeout.
Otherwise, here's my SwipeList and SwipeListRow component. I partially use my library Cairn for styling, but it should be easily translated into a normal React Stylesheet if you care to do so:
SwipeList.js
import React from 'react';
import { Text, ListView } from 'react-native';
import styleContext from 'app/style';
const style = styleContext.extend({
listViewSection: {
paddingVertical: 10,
paddingLeft: 15,
backgroundColor: '$greyDefault'
},
'text.listViewSection': {
color: '$greyMid',
fontSize: 16,
marginLeft: 5
}
});
function SwipeList({ dataSource, renderRow }) {
function renderSectionHeader(sectionData, sectionId) {
return (
<View {...style('listViewSection')}>
<Text {...style('text.listViewSection')}>{sectionId.toUpperCase()}</Text>
</View>
);
}
if (!dataSource.rowIdentities.length) {
return (
<Text>No items found.</Text>
);
}
return (
<ListView
dataSource={dataSource}
automaticallyAdjustContentInsets={false}
directionalLockEnabled
keyboardShouldPersistTaps={false}
keyboardDismissMode={'on-drag'}
renderSectionHeader={renderSectionHeader}
renderRow={renderRow} />
);
}
SwipeList.propTypes = {
dataSource: React.PropTypes.shape({
rowIdentities: React.PropTypes.array.isRequired
}).isRequired,
renderRow: React.PropTypes.func.isRequired
};
export default SwipeList;
SwipeListRow.js
import React from 'react';
import {
View,
Text,
ScrollView,
Animated,
Dimensions
} from 'react-native';
import styleContext from 'app/style';
const { width } = Dimensions.get('window');
const style = styleContext.extend({
swipeMessage: {
position: 'absolute',
top: 0,
height: 75,
justifyContent: 'center',
alignItems: 'center'
},
itemContainer: {
width
}
});
const WHITE = 0;
const GREEN = 1;
const AnimatedScrollView = Animated.createAnimatedComponent(ScrollView);
class SwipeListRow extends React.Component {
constructor(props) {
super(props);
this.state = {
color: new Animated.Value(WHITE)
};
}
animateScroll = (e) => {
const threshold = width / 5;
let x = e.nativeEvent.contentOffset.x;
let swiped = null;
x = x * -1;
if (x > -50 && this.swiped !== WHITE) {
swiped = WHITE;
} else if (x < -50 && x > -threshold && this.swiped !== GREEN) {
swiped = GREEN;
}
if (swiped !== null) {
this.swiped = swiped;
Animated.timing(this.state.color, {
toValue: swiped,
duration: 200
}).start();
}
}
takeAction = () => {
if (this.swiped) {
Animated.timing(this.state.color, {
toValue: WHITE,
duration: 200
}).start();
this.props.onSwipe();
}
}
render() {
const { swipeEnabled, swipeMessage, children } = this.props;
const bgColor = this.state.color.interpolate({
inputRange: [
WHITE,
GREEN
],
outputRange: [
'rgb(255, 255, 255)',
'rgb(123, 204, 40)'
]
});
return (
<View>
<AnimatedScrollView
horizontal
directionalLockEnabled
automaticallyAdjustContentInsets={false}
onScroll={this.animateScroll}
scrollEventThrottle={16}
scrollEnabled={swipeEnabled}
onMomentumScrollBegin={this.takeAction}
style={[{ flex: 1 }, { backgroundColor: bgColor }]}>
<View>
<View {...style('itemContainer')}>
{children}
</View>
<View
{...style(
'swipeMessage',
[{ width: width / 5, right: -width / 5 - 20 }]
)}>
<Text {...style('text.bold text.white')}>{swipeMessage}</Text>
</View>
</View>
</AnimatedScrollView>
</View>
);
}
}
SwipeListRow.propTypes = {
children: React.PropTypes.node.isRequired,
onSwipe: React.PropTypes.func.isRequired,
swipeEnabled: React.PropTypes.bool.isRequired,
swipeMessage: React.PropTypes.string.isRequired
};
export default SwipeListRow;
With these components, now all you must do is pass in the required datasource as you would to a normal list view, as described on the ListView component documentation.
<SwipeList
dataSource={dataSource}
renderRow={(item) => (
<SwipeListRow
key={item.id}
swipeMessage={'Delete Item'}
onSwipe={() => deleteItem(item)}
swipeEnabled={true}>
<<< INSERT DISPLAY OF ROW HERE >>>
</SwipeListRow>
)} />

use this one
react-native-swipe-list-view
This works really good and you can scale to anything.

Related

React Native and map

I have an issue in my project. I want to show elements after I get them from the JSON. When I am trying to observe content of JSON I see it, but when I am trying to show it in my component it doesn't appear. Also debugger don't show any errors or problrms and app compiles sucessfully. I am really stuck, so I really need your help guys
App.js code:
import React, { Component } from 'react'
import { View, ScrollView, StyleSheet } from 'react-native'
import { Header, ImageCard } from './src/components/uikit'
const url = 'https://s3.eu-central-1.wasabisys.com/ghashtag/RNForKids/00-Init/data.json'
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
title: 'STAR GATE',
data: []
};
}
componentDidMount = async () => {
try {
const response = await fetch(url)
const data = await response.json()
this.setState({ data })
}
catch (e) {
console.log(e)
throw e
}
}
render() {
const { title, data } = this.state
const { container } = style
return (
<View>
<Header title={title} />
<ScrollView>
<View style={container}>
{data.map(item => {
<ImageCard data={item} key={item.id} />
})
}
</View>
</ScrollView>
</View>
)
}
}
const style = StyleSheet.create({
container: {
marginTop: 30,
flexDirection: 'row',
flexWrap: 'wrap',
flexShrink: 2,
justifyContent: 'space-around',
marginBottom: 150,
backgroundColor: 'gold',
width: 150
}
})
My problem happens in App.js inside the
And ImageCard code:
import React from 'react'
import { Image, View, Text, StyleSheet } from 'react-native'
import { h, w } from '../../../constants'
const ImageCard = ({data}) => {
const {container, sub, h2, cover} = styles
const {image, name} = data
return (
<View style={container}>
<View style={sub}>
<Image
style={cover}
source={{
uri: image,
}}
/>
</View>
<Text style={h2}>{name.toUpperCase()}</Text>
</View>
)
}
const styles = StyleSheet.create({
container: {
width: w / 2.1,
paddingVertical: 10,
},
sub: {
padding:10,
shadowColor: 'black',
shadowRadius: 8,
shadowOffset: { width: 0, height: 5 },
shadowOpacity: 0.4,
},
h2: {
fontFamily: 'AvenirNext-DemiBold',
fontSize: 16,
alignSelf: 'center',
textAlign: 'center',
width: w / 2.4
},
cover: {
width: w / 2.4,
height: w * 0.63,
borderRadius: 10
}
})
export { ImageCard }
It should be ok, I made it by guide, but something went wrong.
It looks like you're not returning anything from map!
data.map(item => {
<ImageCard data={item} key={item.id} />
})
should become
data.map(item => {
return <ImageCard data={item} key={item.id} />
})
// OR
data.map(item => ( // <-- Note the bracket change
<ImageCard data={item} key={item.id} />
))

Basic react native question covert Class to Function

It might sound silly but I am just learning here
I am trying to convert a component to a function-based component. I did everything right but I am stuck on something very silly
I have this code for Discover
export default class Discover extends React.PureComponent {
state = {
items: [],
};
cellRefs: {};
constructor(props) {
super(props);
this.cellRefs = {};
}
what is the correct way to convert cellRefs to work with the function I have? I tried everything when I do this in my class file it is fine it gives me an object with the things I need.
const cell = this.cellRefs[item.key];
However,
const cell = cellRefs[item.key];
is just giving undefined
Full code for the converted component
import React, { useState, useEffect, useRef, Children } from 'react';
import {
StyleSheet,
Text,
View,
FlatList,
Dimensions,
TouchableOpacity,
Image,
} from 'react-native';
import { Video } from 'expo-av';
const { height, width } = Dimensions.get('window');
const cellHeight = height * 0.6;
const cellWidth = width;
const viewabilityConfig = {
itemVisiblePercentThreshold: 80,
};
class Item extends React.PureComponent {
video: any;
componentWillUnmount() {
if (this.video) {
this.video.unloadAsync();
}
}
async play() {
const status = await this.video.getStatusAsync();
if (status.isPlaying) {
return;
}
return this.video.playAsync();
}
pause() {
if (this.video) {
this.video.pauseAsync();
}
}
render() {
const { id, poster, url } = this.props;
const uri = url + '?bust=' + id;
return (
<View style={styles.cell}>
<Image
source={{
uri: poster,
cache: 'force-cache',
}}
style={[styles.full, styles.poster]}
/>
<Video
ref={ref => {
this.video = ref;
}}
source={{ uri }}
shouldPlay={false}
isMuted
isLooping
resizeMode="cover"
style={styles.full}
/>
<View style={styles.overlay}>
<Text style={styles.overlayText}>Item no. {id}</Text>
<Text style={styles.overlayText}>Overlay text here</Text>
</View>
</View>
);
}
}
interface FeedListProps {
}
export const FeedList: React.FC<FeedListProps> = (props) => {
const initialItems = [
{
id: 1,
url: 'https://s3.eu-west-2.amazonaws.com/jensun-uploads/shout/IMG_1110.m4v',
poster:
'https://s3.eu-west-2.amazonaws.com/jensun-uploads/shout/norwaysailing.jpg',
},
{
id: 2,
url:
'https://s3.eu-west-2.amazonaws.com/jensun-uploads/shout/croatia10s.mp4',
poster:
'https://s3.eu-west-2.amazonaws.com/jensun-uploads/shout/croatia10s.jpg',
},
];
const [items, setItems] = useState([]);
//this.cellRefs = {};
//let cellRefs: {};
//cellRefs= {};
const cellRefs = React.useRef({})
const viewConfigRef = React.useRef({ itemVisiblePercentThreshold: 80 })
useEffect(() => {
loadItems();
setTimeout(loadItems, 1000);
setTimeout(loadItems, 1100);
setTimeout(loadItems, 1200);
setTimeout(loadItems, 1300);
}, []);
const _onViewableItemsChanged = React.useRef((props)=>{
const changed = props.changed;
changed.forEach(item => {
const cell = cellRefs[item.key];
console.log("CALLING IF"+ cell + " " + item.key)
if (cell) {
if (item.isViewable) {
console.log("PLAY OS CALLED")
cell.play();
} else {
console.log("Pause is played")
cell.pause();
}
}
});
});
function loadItems(){
const start = items.length;
const newItems = initialItems.map((item, i) => ({
...item,
id: start + i,
}));
const Litems = [...items, ...newItems];
setItems( Litems );
};
function _renderItem({ item }){
return (
<Item
ref={cellRefs[item.id]}
{...item}
/>
);
};
return (
<View style={styles.container}>
<FlatList
style={{ flex: 1 }}
data={items}
renderItem={_renderItem}
keyExtractor={item => item.id.toString()}
onViewableItemsChanged={_onViewableItemsChanged.current}
initialNumToRender={3}
maxToRenderPerBatch={3}
windowSize={5}
getItemLayout={(_data, index) => ({
length: cellHeight,
offset: cellHeight * index,
index,
})}
viewabilityConfig={viewabilityConfig}
removeClippedSubviews={true}
ListFooterComponent={
<TouchableOpacity onPress={loadItems}>
<Text style={{ padding: 30 }}>Load more</Text>
</TouchableOpacity>
}
/>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
},
cell: {
width: cellWidth - 20,
height: cellHeight - 20,
backgroundColor: '#eee',
borderRadius: 20,
overflow: 'hidden',
margin: 10,
},
overlay: {
position: 'absolute',
top: 0,
right: 0,
bottom: 0,
left: 0,
backgroundColor: 'rgba(0,0,0,0.4)',
padding: 40,
},
full: {
position: 'absolute',
top: 0,
right: 0,
bottom: 0,
left: 0,
},
poster: {
resizeMode: 'cover',
},
overlayText: {
color: '#fff',
},
});
Should be enough to use a functional component and use useRef([]) initialized as an array
Working example:
https://snack.expo.io/2_xrzF!LZ
It would be best if you could inline your source code into stack overflow, than keeping it in a separate link. However I took a look at the component, and I think the issue is with how you are using props.
On line 91,
export const FeedList: React.FC<FeedListProps> = ({}) => {
So here, you need to get the props as an argument. Earlier with the class component it was available at this.props. However here you need to pass it as below,
export const FeedList: React.FC<FeedListProps> = (props) => {
Or you may destructure the props as below,
export const FeedList: React.FC<FeedListProps> = ({changed}) => {
You will also need to modify the interface on line 87 to reflect the type.

Add WebView via onClick in Expo React-Native

I need a function that creates new screens with a webview in it.
The main screen of my expo app contains a button "add new Page" which links to a page with a form to add domain, Username, Password.
if this is done, I want a list of pages in my main screen with all pages. for example if I click on "myWebsite1" with the generated link http://user:password#myWebsite1.com this page should be shown in a webview. same for website2, 3 and so on.
Anyone an idea how to do this?
EDIT: I add some code I have right now. For each Task I create, the Domain, User and Password for the webview file should change and be saved at this specific task. (and also open onclick). I turn in a circle
this is my app.js which expo opens first, it contains a Flatlist:
import React, { Component } from "react";
import { AppRegistry, StyleSheet, Text, View, FlatList, AsyncStorage, Button, TextInput, Keyboard, Platform, TouchableWithoutFeedback } from "react-native";
const isAndroid = Platform.OS == "android";
const viewPadding = 10;
const things = {things}
export default class NodeList extends Component {
state = {
tasks: [ ],
text: ""
};
changeTextHandler = text => {
this.setState({ text: text });
};
addTask = () => {
let notEmpty = this.state.text.trim().length > 0;
if (notEmpty) {
this.setState(
prevState => {
let { tasks, text } = prevState;
return {
tasks: tasks.concat({ key: tasks.length, text: text }),
text: ""
};
},
() => Tasks.save(this.state.tasks)
);
}
};
deleteTask = i => {
this.setState(
prevState => {
let tasks = prevState.tasks.slice();
tasks.splice(i, 1);
return { tasks: tasks };
},
() => Tasks.save(this.state.tasks)
);
};
componentDidMount() {
Keyboard.addListener(
isAndroid ? "keyboardDidShow" : "keyboardWillShow",
e => this.setState({ viewMargin: e.endCoordinates.height + viewPadding })
);
Keyboard.addListener(
isAndroid ? "keyboardDidHide" : "keyboardWillHide",
() => this.setState({ viewMargin: viewPadding })
);
Tasks.all(tasks => this.setState({ tasks: tasks || [] }));
}
render() {
return (
<View
style={[styles.container, { paddingBottom: this.state.viewMargin }]}
>
<Text style={styles.appTitle}>Nodes</Text>
<FlatList
style={styles.list}
data={this.state.tasks}
renderItem={({ item, index }) =>
<View>
<View style={styles.listItemCont}>
<TouchableWithoutFeedback onPress={() => Linking.openURL('')}>
<Text style={styles.listItem}>
{item.text}
</Text>
</TouchableWithoutFeedback>
<Button color= "#00BC8C" title="✖" onPress={() => this.deleteTask(index)} />
</View>
<View style={styles.hr} />
</View>}
/>
<TextInput
style={styles.textInput}
onChangeText={this.changeTextHandler}
onSubmitEditing={this.addTask}
value={this.state.text}
placeholder="+ add Node"
returnKeyType="done"
returnKeyLabel="done"
/>
</View>
);
}
}
let Tasks = {
convertToArrayOfObject(tasks, callback) {
return callback(
tasks ? tasks.split("||").map((task, i) => ({ key: i, text: task })) : []
);
},
convertToStringWithSeparators(tasks) {
return tasks.map(task => task.text).join("||");
},
all(callback) {
return AsyncStorage.getItem("TASKS", (err, tasks) =>
this.convertToArrayOfObject(tasks, callback)
);
},
save(tasks) {
AsyncStorage.setItem("TASKS", this.convertToStringWithSeparators(tasks));
}
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: "center",
alignItems: "center",
backgroundColor: "#252525",
padding: viewPadding,
paddingTop: 24
},
list: {
width: "100%"
},
listItem: {
paddingTop: 4,
paddingBottom: 2,
fontSize: 18,
color:"#ffff"
},
hr: {
height: 1,
backgroundColor: "gray"
},
listItemCont: {
flexDirection: "row",
alignItems: "center",
justifyContent: "space-between",
paddingTop: 10,
},
textInput: {
height: 40,
paddingRight: 10,
paddingLeft: 10,
borderColor: "gray",
borderWidth: isAndroid ? 0 : 1,
width: "100%",
color:"#ffff"
},
appTitle: {
alignItems:"center",
justifyContent: "center",
paddingBottom: 45,
marginTop: 50,
fontSize: 25,
color:"#ffff"
}
});
AppRegistry.registerComponent("NodeList", () => NOdeList);
and here is my second screen, which contains the component for the WebView:
import React, { Component, useState } from "react";
import { BackHandler } from 'react-native';
import { WebView } from 'react-native-webview';
var $ = require( "jquery" );
export default class nodeView extends Component {
constructor(props) {
super(props);
this.WEBVIEW_REF = React.createRef();
}
componentDidMount() {
BackHandler.addEventListener('hardwareBackPress', this.handleBackButton);
}
componentWillUnmount() {
BackHandler.removeEventListener('hardwareBackPress', this.handleBackButton);
}
handleBackButton = ()=>{
this.WEBVIEW_REF.current.goBack();
return true;
}
onNavigationStateChange(navState) {
this.setState({
canGoBack: navState.canGoBack
});
}
render(){
return (
<WebView
source={{ uri: `https://${user}:${password}#${domain}` }}
ref={this.WEBVIEW_REF}
style={{ marginTop: 20 }}
onNavigationStateChange={this.onNavigationStateChange.bind(this)}
/>
)
}
}
Create WebView. Create State Which Controls WebView. Add Listener To Button

How to run a funtion onclick of button from one component and funtion run on another compoenent in react native

Code of Home.js
import React, { Component } from 'react'
import { Text, View, Alert } from 'react-native'
import { Card, Title, Paragraph, Button } from 'react-native-paper';
import Animater from '../component/Animater'
import FontAwesome5 from 'react-native-vector-icons/FontAwesome5';
import { act } from 'react-test-renderer';
const data = [
{
id: 1,
q: "Is you age above 50 or below 10",
uri: 'https://miro.medium.com/max/524/1*Peqrh5C9f4lSNNBiwguxTw.png',
},
{
id: 2,
q: "Do You Visited Forign before 15 March?",
uri: 'https://www.howitworksdaily.com/wp-content/uploads/2015/07/68_1.jpg'
},
...
{
id: 9,
q: "Do you meet any Foreigner or NRI",
uri: 'https://assets3.thrillist.com/v1/image/2079046/size/tmg-article_default_mobile_2x.jpg',
}
]export default class CheckCorona extends Component {
constructor(props){
super(props)
}
ButtonPressed=()=>{
console.log("yess it is working")
}
renderCard(item) {
return (
<View key={item.id}>
<Card>
<Card.Content>
<Title style={{ marginHorizontal: 15, fontSize: 24 }}>Q{item.id}: {item.q}</Title>
<Card.Cover source={{ uri: item.uri }} />
<Card.Actions>
<Button onPress={()=>this.ButtonPressed()} >Yess</Button>
<Button>No</Button>
</Card.Actions>
</Card.Content>
</Card>
</View>
)
}
ShowResult = () => {
return (
<Card>
<Title>Tu Single is thik hai</Title>
</Card>
)
}
render() {
return (
<View>
<Animater
data={data}
renderCard={this.renderCard}
ShowResult={this.ShowResult}
ButtonPressed={this.ButtonPressed}
/>
</View>
)
}
}
and Code of Animate.js is
import React, { Component } from 'react'
import { Text, View, PanResponder, Animated, Dimensions, StyleSheet, Alert } from 'react-native'
const Screen_width = Dimensions.get('window').width;
const Swipe_Limit = Screen_width / 2;
export default class Animater extends Component {
constructor(props) {
super(props)
this.state = {
index: 0
}
const position = new Animated.ValueXY();
this.PanResponder = PanResponder.create({
onStartShouldSetPanResponder: () => true,
onPanResponderMove: (e, gesture) => {
position.setValue({ x: gesture.dx, y: gesture.dy })
},
onPanResponderRelease: (e, gesture) => {
if (gesture.dx > Swipe_Limit) {
this.swipe("right")
} else if (gesture.dx < -Swipe_Limit) {
this.swipe("Left")
} else {
this.resetPosition()
}
}
})
this.position = position
}
DoSwiable = () => {
// const newCheck= 'this.swipe("right")'
if(this.props.ButtonPressed()){
console.log("hello")
}
}
swipe = (direction) => {
const x = direction === 'right' ? Screen_width * 3 : -Screen_width * 3
Animated.timing(this.position, {
toValue: { x: x, y: 0 }
}).start(() => {
this.position.setValue({ x: 0, y: 0 }),
this.setState({
index: this.state.index + 1
})
})
}
resetPosition = () => {
Animated.spring(this.position, {
toValue: { x: 0, y: 0 }
}).start()
}
mycardstyle = () => {
const rotate = this.position.x.interpolate({
inputRange: [-Screen_width, 0, Screen_width],
outputRange: ['-120deg', '0deg', '120deg']
})
return {
...this.position.getLayout(),
transform: [{ rotate: rotate }]
}
}
rendercard = () => {
if (this.state.index >= this.props.data.length) {
return this.props.ShowResult()
}
return this.props.data.map((item, i) => {
if (i < this.state.index) {
return null
}
if (i === this.state.index) {
return (
<Animated.View key={i}
style={[this.mycardstyle(), styles.cardStyle]}
{...this.PanResponder.panHandlers}>
{this.props.renderCard(item)}
</Animated.View>
)
}
return (
<View key={item.id} style={[styles.cardStyle, { top: 5 * (i - this.state.index) }]}>
{this.props.renderCard(item)}
</View>
)
}).reverse()
}
render() {
return (
<View>
{this.rendercard()}
</View>
)
}
}
const styles = StyleSheet.create({
cardStyle: {
position: "absolute",
zIndex: 1,
width: Screen_width
}
})
Actually it is swipeable card I want that when Yes button on Home.js pressed then function on animated.js should run this.swipe("right")
Actually I have used props for the showing the data and so the main screen is Home.js and I have import the Animater.js and pass some function is a props and then I am running the props.
Change
ButtonPressed=()=>{
console.log("yess it is working")
}
to
ButtonPressed=()=>{
console.log("yess it is working");
(new Animater()).swipe("right");
}
Hope this helps you!

react-native-swiper button is not work properly

Issue
The blue active button below is not updated when the react-native-swiper moves as shown below.
For swiper I'm creating a view using the map() function.
Note that passing the key (index) to the child view component does not update the blue button.
If I hardcode the view without using the map() function in swiper, the button will work.
What's the problem?
References Photo
My Code
import React from 'react';
import { View, Platfrom, Text, StyleSheet, AsyncStorage, TouchableOpacity, Image, FlatList, ScrollView } from 'react-native';
import Icon from 'react-native-vector-icons/FontAwesome';
import { connect } from 'react-redux';
import moment from 'moment';
import Swiper from 'react-native-swiper';
import * as settings from '../../config/settings';
const styles = StyleSheet.create({
headerRight: {
padding: 10
},
body_txt: {
marginTop: 5,
padding: 8,
borderWidth: 1,
borderColor: '#EAEAEA',
},
slidmain: {
borderColor: '#EAEAEA',
borderWidth: 1,
},
slide1: {
width: '100%',
height: 300,
},
main: {
flex: 1,
backgroundColor: '#FFFFFF',
padding: 10,
},
image: {
height: 100,
width: '98%',
marginBottom: 70,
marginLeft: '1%',
resizeMode: 'contain',
}
});
class RepairInquiryDetailScreen extends React.Component {
constructor(props) {
super(props);
this.state = {
created_date: '',
photos: [],
key: 0,
}
}
static navigationOptions = ({ navigation }) => ({
title: '수선 문의서',
headerStyle: {
backgroundColor: '#fff',
borderBottomWidth: 0,
elevation: 0,
},
headerTitleStyle: {
color: '#000',
fontSize: 20,
textAlign: 'center',
alignSelf: 'center',
},
headerRight: <Icon name="bars" size={30} color="#333" onPress={() => navigation.navigate('DrawerOpen')} style={styles.headerRight} />
})
RepairInquiryDetailService = async () => {
let user_info = await AsyncStorage.getItem('user_info');
user_token = JSON.parse(user_info).key;
let inquiry_id = this.props.navigation.state.params.id
const api_uri = settings.base_uri + 'inquiry/' + inquiry_id + '/'
fetch(api_uri, {
method: 'GET',
headers: {
'Authorization': 'Token ' + user_token,
}
})
.then(res => res.json())
.then(res => {
let repair_type_tmp = ""
for (i = 0; i < res.repair_type.length; i++) {
if (i == 0) {
repair_type_tmp += res.repair_type[i].type;
} else {
repair_type_tmp += ", " + res.repair_type[i].type;
}
}
let photos_tmp = [];
for (i = 0; i < res.photos.length; i++) {
photos_tmp[i] = res.photos[i].thumbnail;
}
let logistics_tmp = "";
if (res.logistics == "delivery") {
logistics_tmp = "택배";
} else if (res.logistics == "quick") {
logistics_tmp = "퀵";
} else if (res.logistics == "direct") {
logistics_tmp = "방문";
} else {
logistics_tmp = res.logistics;
}
this.setState({
product_type: res.product_type.type,
repair_type: repair_type_tmp,
model: res.model,
content: res.content,
logistics: logistics_tmp,
created_date: res.created_date,
direct_partner: res.direct_partner,
photos: photos_tmp,
})
console.log(this.state.photos)
})
.catch((error) => {
console.error(error);
});
}
componentDidMount() {
this.RepairInquiryDetailService();
}
render() {
const parsedDate = moment(this.state.created_date).format("YYYY.MM.DD")
return (
<ScrollView style={styles.main}>
<Swiper
style={styles.slidmain}
height={300}
showsButtons={false}
loop={false}
>
{this.state.photos.map((item, key) => {
console.log(item, key);
return (
<Slide uri={item} key={key} i={key}/>
);
})}
</Swiper>
<View style={styles.body_txt}>
<Text>제품 카테고리: {this.state.product_type}</Text>
<Text>수선 카테고리: {this.state.repair_type}</Text>
<Text>모델명: {this.state.model}</Text>
<Text>배송유형: {this.state.logistics}</Text>
<Text>작성일: {parsedDate}</Text>
<Text>문의 상세내용: {this.state.content}</Text>
</View>
</ScrollView>
)
}
}
const Slide = props => {
console.log('uri and key: ', props.uri, props.i);
return (
<View style={styles.slide1} key={props.i}>
<Image
source={{ uri: props.uri }}
style={styles.slide1}
/>
</View>
);
}
const mapStateToProps = state => ({
isLoggedIn: state.loginReducer.isLoggedIn
})
const RepairInquiryDetail = connect(mapStateToProps, null)(RepairInquiryDetailScreen);
export default RepairInquiryDetail;
Thanks!
A suggested fix to this problem, found here, is to remove the style prop from your Swiper component.
To get your desired border you could wrap your swiper in a parent view. Hope this helps.

Categories

Resources