react-native-swiper button is not work properly - javascript

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.

Related

How to handle volumes of multiple track in react-native sound, i want to play 2 sound together and if i want to decrease sound of one

Here is my code screen code
import React, {Component} from 'react';
import {StyleSheet, Text, TouchableOpacity, View, ScrollView, Alert} from 'react-native';
import Sound from 'react-native-sound';
import BgSoundPlayer from '../../../../Components/BgSoundPlayer/BgSoundPlayer';
const audioTests = [
{
title: 'mp3 remote download',
url: 'https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3',
},
{
title: "mp3 remote - file doesn't exist",
url: 'https://www.soundhelix.com/examples/mp3/SoundHelix-Song-9.mp3',
},
];
const Button = ({title, onPress}) => (
<TouchableOpacity onPress={onPress}>
<Text style={styles.button}>{title}</Text>
</TouchableOpacity>
);
const Header = ({children, style}) => <Text style={[styles.header, style]}>{children}</Text>;
const Feature = ({
title,
onPress,
buttonLabel = 'PLAY',
status,
volumeIncrease,
volumeDecrease,
}) => (
<View style={styles.feature}>
<Header style={{flex: 1}}>{title}</Header>
{status ? <Text style={{padding: 5}}>{resultIcons[status] || ''}</Text> : null}
<Button title={buttonLabel} onPress={onPress} />
<Button title="Volume Increase" onPress={volumeIncrease} />
<Button title="volume Decrease" onPress={volumeDecrease} />
</View>
);
const resultIcons = {
'': '',
pending: '?',
playing: '\u25B6',
win: '\u2713',
fail: '\u274C',
};
function setTestState(testInfo, component, status) {
component.setState({tests: {...component.state.tests, [testInfo.title]: status}});
}
/**
* Generic play function for majority of tests
*/
function playSound(testInfo, component) {
setTestState(testInfo, component, 'pending');
BgSoundPlayer.setSound(testInfo);
}
class MainView extends Component {
constructor(props) {
super(props);
Sound.setCategory('Playback', true); // true = mixWithOthers
// Special case for stopping
this.stopSoundLooped = () => {
if (!this.state.loopingSound) {
return;
}
this.state.loopingSound.stop().release();
this.setState({
loopingSound: null,
tests: {...this.state.tests, ['mp3 in bundle (looped)']: 'win'},
});
};
this.state = {
loopingSound: undefined,
tests: {},
};
}
render() {
return (
<View style={styles.container}>
<ScrollView style={styles.container} contentContainerStyle={styles.scrollContainer}>
{audioTests.map(testInfo => {
return (
<Feature
status={this.state.tests[testInfo.title]}
key={testInfo.title}
title={testInfo.title}
onPress={() => {
playSound(testInfo, this);
}}
volumeIncrease={() => {
BgSoundPlayer.increaseVolume();
}}
volumeDecrease={() => {
BgSoundPlayer.decreaseVolume();
}}
/>
);
})}
<Feature
title="mp3 in bundle (looped)"
buttonLabel={'STOP'}
onPress={() => {
BgSoundPlayer.pouse();
}}
/>
</ScrollView>
</View>
);
}
}
export default MainView;
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: 'gray',
},
scrollContainer: {},
title: {
fontSize: 20,
fontWeight: 'bold',
paddingTop: 30,
padding: 20,
textAlign: 'center',
backgroundColor: 'rgba(240,240,240,1)',
},
button: {
fontSize: 20,
backgroundColor: 'rgba(220,220,220,1)',
borderRadius: 4,
borderWidth: 1,
borderColor: 'rgba(80,80,80,0.5)',
overflow: 'hidden',
padding: 7,
},
header: {
textAlign: 'left',
},
feature: {
padding: 10,
borderTopWidth: 1,
borderBottomWidth: 1,
},
});
And my BgSoundPlayer file
import {Alert} from 'react-native';
import Sound from 'react-native-sound';
Sound.setCategory('Playback', true);
class BgSoundPlayer1 {
setSound(soundURL) {
try {
this.soundURL = soundURL;
if (soundURL.isRequire) {
this.soundRef = new Sound(soundURL.url, error =>
this.callback(error, this.soundRef),
);
} else {
this.soundRef = new Sound(soundURL.url, Sound.MAIN_BUNDLE, error =>
this.callback(error, this.soundRef),
);
}
} catch (error) {
console.log('SOUNDREFERROR::', error);
}
}
callback(error, sound) {
try {
if (error) {
Alert.alert('error', error.message);
return;
}
//this.soundURL.onPrepared && this.soundURL.onPrepared(sound);
sound.play(() => {
sound.release();
});
} catch (error) {
console.log('CALL_BACKERROR::', error);
}
}
getVolume() {
return this.soundRef?.getVolume();
}
increaseVolume(soundURL) {
console.log('CHECKREF', this.soundRef);
let sound = this.soundRef?.getVolume();
if (sound < 1 || sound == 1) {
this.soundRef?.setVolume(sound + 0.1);
}
}
decreaseVolume(soundURL) {
console.log('CHECKREF', this.soundRef);
let sound = this.soundRef?.getVolume();
if (sound > 0 || sound == 0) {
this.soundRef?.setVolume(sound - 0.1);
}
}
pouse() {
this.soundRef?.pause();
}
}
const BgSoundPlayer = new BgSoundPlayer1();
export default BgSoundPlayer;
So what is happening right now if, when I am playing one audio track and increasing decreasing volume of track its working fine
but problem occurre's when I play second track and decrease sound of first one, it dosent works it decrease volume of second track
but when I tried to debug problem, I got to know that my this.soundRef variable is taking the refrance of latest one sound, so how can solve this

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 delete particular list item locally and from server after swipe in react native

// Here in my code am calling 2 APIS 1.( createViewGroup = async () =>)one for get data from server and set on FlatList , id,sensorType inventory,
2 second api ("SensorDelt = (rowIndex) => ") am calling for delete particular list iteam from server ,I mean after touching particular list item , i am taking id no and that id ({"password":"admin","username":"admin","sensorid":"here i have to send id no"})am sending to server and that id will be delete .
In my code am using Swipeout delete button to delete list item ,but it is working locally, not deleting from server .
Please help
import * as React from "react";
import {
View,
Text,
TextInput,
FooterTab,
Button,
TouchableOpacity,
ScrollView,
StyleSheet,
ActivityIndicator,
Header,
Alert,
AsyncStorage,
FlatList
} from "react-native";
import { Table, Row, Rows } from "react-native-table-component";
import { createStackNavigator, createAppContainer } from "react-navigation";
import { SearchBar } from "react-native-elements";
// You can import from local files
//import AssetExample from './components/AssetExample';
// or any pure javascript modules available in npm
import { Card } from "react-native-paper";
import Swipeout from "react-native-swipeout";
class OpenApplianceIssue extends React.Component {
constructor() {
super();
this.state = {
AbcSdata: null,
loading: true,
search: "",
tableData: [],
qrData: "",
selectedPriority: "",
selectedIssue: "",
selectedReason: "",
selectedTriedRestart: "",
selectedPowerLED: "",
selectedBurning: "",
selectedNoise: "",
rowID: "",
activeRow: null
};
this.setDate = this.setDate.bind(this);
}
swipeBtns = [
{
text: "Delete",
type: "delete",
backgroundColor: "red",
underlayColor: "rgba(0, 0, 0, 1, 0.6)",
onPress: () => {
console.log("Deleting Row with Id ", this.state.activeRow);
{
this.deleteNote(this.state.activeRow);
this.onClickListener("del");
}
}
//onPress:() => this.onClickListener('tag')}
}
];
removeItem = (items, i) =>
items.slice(0, i).concat(items.slice(i + 1, items.length));
deleteNote = rowIndex => {
//add your custome logic to delete the array element with index.
// this will temporary delete from the state.
let filteredData = this.removeItem(this.state.AbcSdata, rowIndex);
this.setState({ AbcSdata: [] }, () => {
this.setState({ AbcSdata: filteredData }, () => {
console.log("Row deleted.", rowIndex);
});
});
};
setDate(newDate) {}
_loadInitialState = async () => {
const { navigation } = this.props;
const qdata = navigation.getParam("data", "NA").split(",");
var len = qdata.length;
const tData = [];
console.log(len);
for (let i = 0; i < len; i++) {
var data = qdata[i].split(":");
const entry = [];
entry.push(`${data[0]}`);
entry.push(`${data[1]}`);
tData.push(entry);
}
this.setState({ tableData: tData });
console.log(this.state.tableData);
this.setState({ loading: true });
};
// Delete Sensors ********************
SensorDelt = rowIndex => {
//const Sensorid_Data = this.props.navigation.state.params.item.id;
let filteredData = this.removeItem(this.state.AbcSdata, rowIndex);
let ABHI = filteredData//const Sensorid_Data = this.state.rowIndex;
.console
.log("Value Abhi" + filteredData);
Alert.alert("Value" + filteredData);
fetch("http:/Dsenze/userapi/sensor/delsensor", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify({
password: "admin",
username: "admin",
sensorid: filteredData
})
})
.then(response => {
//console.log(response);
return response.json();
})
.then(res => {
if (res.success == "true") {
Alert.alert("Sensor Added");
this.props.navigation.replace("OpenApplianceIssue");
} else {
Alert.alert("Success false");
}
});
};
handleValueChange(SensortypeId) {
this.setState({ SensortypeId });
}
// Delete sensors ***********************
onClickListener = viewId => {
if (viewId == "tag") {
this.props.navigation.navigate("AddSensors");
} else if (viewId == "del") {
//this.props.navigation.navigate('AddSensors');
this.SensorDelt();
}
};
componentDidMount() {
//this._loadInitialState().done();
this.createViewGroup();
}
// Get Sensor list ********************************************
createViewGroup = async () => {
try {
const response = await fetch(
"http://Dsenze/userapi/sensor/viewsensor",
{
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify({
password: "admin",
username: "admin",
startlimit: "0",
valuelimit: "10"
})
}
);
const responseJson = await response.json();
const { sensorData } = responseJson;
this.setState({
AbcSdata: sensorData,
loading: false
});
} catch (e) {
console.error(e);
}
};
clickedItemText(OpenApplianceIssue) {
this.props.navigation.navigate("Item007", { item: OpenApplianceIssue });
//Abc = this.props.navigation.state.params.item.id;
}
updateSearch = search => {
this.setState({ search });
};
keyExtractor = ({ id }) => id.toString();
keyExtractor = ({ inventory }) => inventory.toString();
onSwipeOpen(rowId, direction) {
if (typeof direction !== "undefined") {
this.setState({ activeRow: rowId });
console.log("Active Row", rowId);
}
}
renderItem = ({ item, index }) => (
<Swipeout
style={styles.SwipeBG}
right={this.swipeBtns}
close={this.state.activeRow !== index}
rowID={index}
sectionId={1}
autoClose={true}
// onOpen = {(secId, rowId, direction) => this.onSwipeOpen(rowId, direction)}
>
<TouchableOpacity
style={styles.item}
activeOpacity={0.4}
onPress={() => {
this.clickedItemText(item);
}}
>
{/* //onPress={this.viewNote(item)} >
> */}
<Text>Id : {item.id}</Text>
<Text>Inventory : {item.inventory}</Text>
<Text>SensorType : {item.sensorType}</Text>
<Text>TypeName : {item.typeName}</Text>
</TouchableOpacity>
</Swipeout>
);
// viewNote =(item) => {
// this.props.navigator.push({
// title: 'The Note',
// component: this.ViewNote,
// passProps: {
// noteText: item,
// noteId: this.noteId(item),
// }
// });
// console.log("View Note Success");
// }
renderSeparator = () => {
return (
<View
style={{
height: 1,
width: "86%",
backgroundColor: "#CED0CE"
}}
/>
);
};
render() {
const { loading, AbcSdata } = this.state;
const state = this.state;
return (
<ScrollView>
<View style={styles.container1}>
<Button
full
rounded
style={{ fontSize: 20, color: "green" }}
styleDisabled={{ color: "red" }}
onPress={() => this.onClickListener("tag")}
title="Add Sensors"
>
Add Sensors
</Button>
</View>
<View style={styles.container1}>
{this.state.loading ? (
<ActivityIndicator size="large" />
) : (
<FlatList
style={styles.ListDATA}
data={AbcSdata}
renderItem={this.renderItem}
keyExtractor={this.keyExtractor}
extraData={this.state.activeRow}
ItemSeparatorComponent={this.renderSeparator}
/>
)}
</View>
<View>
<Text
style={{ alignSelf: "center", fontWeight: "bold", color: "black" }}
>
Inventory Details
</Text>
<Table
borderStyle={{
borderWidth: 2,
borderColor: "#c8e1ff",
padding: 10,
paddingBottom: 10
}}
>
<Rows data={state.tableData} textStyle={styles.text} />
</Table>
</View>
</ScrollView>
);
}
}
export default (OpenApplianceIssue = createStackNavigator({
Item007: { screen: OpenApplianceIssue }
}));
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: "center",
backgroundColor: "#ecf0f1",
padding: 8
},
paragraph: {
margin: 24,
fontSize: 18,
fontWeight: "bold",
textAlign: "center"
},
SwipeBG: {
backgroundColor: "#ffffff",
marginLeft: 7,
marginTop: 3
},
ListDATA: {
backgroundColor: "#ffffff",
marginLeft: 5,
marginTop: 3
}
});
Thanks

How to solve the problem for stackNavigator

Here In this code I am populating json data on ListView ..and after click item value, passing that particular value on new screen.. .
I have created MainActivity where I am populating JSON value and on SecondActivity sendng selected item value ,
To navigate between class I am using
export default MyNewProject = StackNavigator(
{
First: { screen: MainActivity },
Second: { screen: SecondActivity }
});
// getting error "undefined is not a function (evaluating '(0 _reactnavigation.stacknavigator)')"..
import React, { Component } from 'react';
import { StyleSheet, Text, View, ListView, ActivityIndicator } from 'react-native';
import { StackNavigator } from 'react-navigation';
class MainActivity extends Component {
constructor(props) {
super(props);
this.state = {
// Default Value of this State.
Loading_Activity_Indicator: true
}
}
componentDidMount() {
return fetch('https://reactnativecode.000webhostapp.com/FruitsList.php')
.then((response) => response.json())
.then((responseJson) => {
let ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
this.setState({
Loading_Activity_Indicator: false,
dataSource: ds.cloneWithRows(responseJson),
}, function() {
// In this block you can do something with new state.
});
})
.catch((errorMsg) => {
console.error(errorMsg);
});
}
ListViewItemSeparator = () => {
return (
<View
style={{
height: .5,
width: "100%",
backgroundColor: "#000",
}}
/>
);
}
Navigate_To_Second_Activity=(fruit_name)=>
{
//Sending the JSON ListView Selected Item Value On Next Activity.
this.props.navigation.navigate('Second', { JSON_ListView_Clicked_Item: fruit_name });
}
static navigationOptions =
{
title: 'MainActivity',
};
render()
{
if (this.state.Loading_Activity_Indicator) {
return (
<View style={styles.ActivityIndicator_Style}>
<ActivityIndicator size = "large" color="#009688"/>
</View>
);
}
return (
<View style={styles.MainContainer}>
<ListView
dataSource={this.state.dataSource}
renderSeparator= {this.ListViewItemSeparator}
renderRow={(rowData) => <Text style={styles.rowViewContainer}
onPress={this.Navigate_To_Second_Activity.bind(this, rowData.fruit_name)} >{rowData.fruit_name}</Text>}
/>
</View>
);
}
}
class SecondActivity extends Component
{
static navigationOptions =
{
title: 'SecondActivity',
};
render()
{
return(
<View style = { styles.MainContainer }>
<Text style = { styles.TextStyle }> { this.props.navigation.state.params.JSON_ListView_Clicked_Item } </Text>
</View>
);
}
}
export default MyNewProject = StackNavigator(
{
First: { screen: MainActivity },
Second: { screen: SecondActivity }
});
const styles = StyleSheet.create(
{
MainContainer:
{
justifyContent: 'center',
flex:1,
margin: 10
},
TextStyle:
{
fontSize: 23,
textAlign: 'center',
color: '#000',
},
rowViewContainer:
{
fontSize: 17,
paddingRight: 10,
paddingTop: 10,
paddingBottom: 10,
},
ActivityIndicator_Style:
{
flex: 1,
alignItems: 'center',
justifyContent: 'center',
left: 0,
right: 0,
top: 0,
bottom: 0,
}
});
// I have tried may thing but not getting the solutions .. I am stuck , this might be small thing but not getting the solutions..
I need help for this ..
Thanks
Try this code
import React, { Component } from 'react';
import { StyleSheet, Text, View, ListView, ActivityIndicator } from 'react-native';
import { createStackNavigator } from 'react-navigation'
class MainActivity extends Component {
constructor(props) {
super(props);
this.state = {
// Default Value of this State.
Loading_Activity_Indicator: true
}
}
componentDidMount() {
return fetch('https://reactnativecode.000webhostapp.com/FruitsList.php')
.then((response) => response.json())
.then((responseJson) => {
let ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
this.setState({
Loading_Activity_Indicator: false,
dataSource: ds.cloneWithRows(responseJson),
}, function() {
// In this block you can do something with new state.
});
})
.catch((errorMsg) => {
console.error(errorMsg);
});
}
ListViewItemSeparator = () => {
return (
<View
style={{
height: .5,
width: "100%",
backgroundColor: "#000",
}}
/>
);
}
Navigate_To_Second_Activity=(fruit_name)=>
{
//Sending the JSON ListView Selected Item Value On Next Activity.
this.props.navigation.navigate('Second', { JSON_ListView_Clicked_Item: fruit_name });
}
static navigationOptions =
{
title: 'MainActivity',
};
render()
{
if (this.state.Loading_Activity_Indicator) {
return (
<View style={styles.ActivityIndicator_Style}>
<ActivityIndicator size = "large" color="#009688"/>
</View>
);
}
return (
<View style={styles.MainContainer}>
<ListView
dataSource={this.state.dataSource}
renderSeparator= {this.ListViewItemSeparator}
renderRow={(rowData) => <Text style={styles.rowViewContainer}
onPress={this.Navigate_To_Second_Activity.bind(this, rowData.fruit_name)} >{rowData.fruit_name}</Text>}
/>
</View>
);
}
}
class SecondActivity extends Component
{
static navigationOptions =
{
title: 'SecondActivity',
};
render()
{
return(
<View style = { styles.MainContainer }>
<Text style = { styles.TextStyle }> { this.props.navigation.state.params.JSON_ListView_Clicked_Item } </Text>
</View>
);
}
}
export default MyNewProject = createStackNavigator (
{
First: { screen: MainActivity },
Second: { screen: SecondActivity }
});
const styles = StyleSheet.create(
{
MainContainer:
{
justifyContent: 'center',
flex:1,
margin: 10
},
TextStyle:
{
fontSize: 23,
textAlign: 'center',
color: '#000',
},
rowViewContainer:
{
fontSize: 17,
paddingRight: 10,
paddingTop: 10,
paddingBottom: 10,
},
ActivityIndicator_Style:
{
flex: 1,
alignItems: 'center',
justifyContent: 'center',
left: 0,
right: 0,
top: 0,
bottom: 0,
}
});
Change your code to this.
import { createStackNavigator } from 'react-navigation';
export default MyNewProject = createStackNavigator(
{
First: { screen: MainActivity },
Second: { screen: SecondActivity }
});
stackNavigator is deprecated, you should use createStackNavigator instead
More info at: https://reactnavigation.org/docs/en/stack-navigator.html
EDIT:
import { createStackNavigator } from 'react-navigation'
export default MyNewProject = createStackNavigator (
{
First: { screen: MainActivity },
Second: { screen: SecondActivity }
});

Categories

Resources