conditionality render headerRight - React Native - reactjs

I have to render headerRight conditionally in navigation options.
Right now
static navigationOptions = ({ navigation }) => ({
title: i18N.t('atmbranchpickHeader'),
headerRight: (
<TouchableHighlight
underlayColor="#E22F39"
onPress={() => {
navigation.navigate("home");
}}
>
<Image
style={{ marginRight: 20 }}
source={require('../../resources/toolbar/home_white.png')}
/>
</TouchableHighlight>
),
headerTintColor: "white",
headerStyle: {
backgroundColor: "#E22F39"
// top: 30
}
});
My Component
import React, { Component } from "react";
import {
View,
TextInput,
Text,
TouchableOpacity,
TouchableHighlight,
StyleSheet,
AsyncStorage,
BackHandler,
Image,
FlatList,
Dimensions,
TouchableWithoutFeedback
} from "react-native";
import i18n from "../../i18n/i18n.js";
import { colors } from "../../constants/colors.js";
import Storage from "../../utils/AsyncStorage.js";
class AtmBranchTypeSelect extends Component {
// Render callBack
constructor(props) {
super(props);
this.state = {
data: [
],
stBool: false,
}
}
async componentWillMount() {
BackHandler.addEventListener('hardwareBackPress', () => this.props.navigation.goBack());
}
componentWillUnmount() {
BackHandler.removeEventListener('hardwareBackPress', () => this.props.navigation.goBack());
}
static navigationOptions = ({ navigation }) => ({
title: i18n.t('atmbranchpickHeader'),
headerRight: (
<TouchableHighlight onPress={() => {
navigation.navigate('home');
}}>
<Image style={{ marginRight: 20 }} source={require('../../resources/toolbar/home_white.png')} />
</TouchableHighlight>),
headerTintColor: 'white',
headerStyle: {
backgroundColor: colors.themeColor,
// top: 30
}
});
_renderList = ({ item }) => {
return (
<TouchableWithoutFeedback onPress={(event) => this._selectedItem(item.key)}>
<View style={styles.listRowContainer}>
<View style={styles.listinside1Container}>
<Image style={styles.listImage} source={item.icon} />
<View style={styles.listContainer} onPress={(event) => this._selectedItem(item.text)} >
<Text style={styles.listHeader} >{item.header}</Text>
<Text style={styles.listValue} >{item.value}</Text>
</View>
</View>
<Image style={styles.listimgArrow} source={require('../../resources/toolbar/chevron_right_grey.png')} />
</View>
</TouchableWithoutFeedback>
);
}
// Render callBack
render() {
return (
<View style={styles.mainWrapper} >
<FlatList data={this.state.data} renderItem={this._renderList} />
</View>
);
}
}
const styles = StyleSheet.create({
mainWrapper: {
flex: 1,
height: Dimensions.get('window').height,
width: Dimensions.get('window').width,
flexDirection: 'column',
justifyContent: 'flex-start'
},
listRowContainer: {
flexDirection: 'row',
marginTop: 10,
height: 80,
backgroundColor: '#FFFFFF',
justifyContent: 'space-between',
borderBottomWidth: 1,
borderColor: 'lightgray'
},
listinside1Container: {
flexDirection: 'row',
justifyContent: 'flex-start',
alignItems: 'center'
},
listContainer: {
alignItems: 'flex-start',
justifyContent: 'center',
flexDirection: 'column',
backgroundColor: '#FFFFFF',
// borderBottomWidth: 1,
// borderColor: 'lightgray'
},
listHeader: {
color: 'black',
fontFamily: 'Roboto-Medium',
marginLeft: 10,
fontSize: 18,
},
listValue: {
fontFamily: 'Roboto-Regular',
marginTop: 4,
color: 'black',
marginLeft: 10,
fontSize: 14,
},
listImage: {
alignSelf: 'center',
height: 25,
width: 25,
margin: 10
},
listimgArrow: {
// flex: 1,
// flexDirection:'row',
alignSelf: 'center',
height: 25,
width: 25,
margin: 10
},
listVal: {
borderWidth: 1,
borderRadius: 10,
color: 'darkgreen',
borderColor: 'white',
backgroundColor: 'white',
fontWeight: 'bold'
},
});
export default AtmBranchTypeSelect;
From the code I have, headerRight will be displayed in all scenarios. consider I have a scenario like based on state value I have to enable/disable headerRight Button .
for example this.state.stBool? headerRight:(.....) : null
I have to render in this way.Please guide me to achieve this.

You could nest the navigation options inside the render and toggle it based on the state value. Haven't tested and not positively on performace. Hope it helps.
import React, { Component } from "react";
import {
View,
TextInput,
Text,
TouchableOpacity,
TouchableHighlight,
StyleSheet,
AsyncStorage,
BackHandler,
Image,
FlatList,
Dimensions,
TouchableWithoutFeedback
} from "react-native";
import i18n from "../../i18n/i18n.js";
import { colors } from "../../constants/colors.js";
import Storage from "../../utils/AsyncStorage.js";
class AtmBranchTypeSelect extends Component {
// Render callBack
constructor(props) {
super(props);
this.state = {
data: [],
stBool: false
};
}
async componentWillMount() {
BackHandler.addEventListener("hardwareBackPress", () =>
this.props.navigation.goBack()
);
}
componentWillUnmount() {
BackHandler.removeEventListener("hardwareBackPress", () =>
this.props.navigation.goBack()
);
}
_renderList = ({ item }) => {
return (
<TouchableWithoutFeedback onPress={event => this._selectedItem(item.key)}>
<View style={styles.listRowContainer}>
<View style={styles.listinside1Container}>
<Image style={styles.listImage} source={item.icon} />
<View
style={styles.listContainer}
onPress={event => this._selectedItem(item.text)}
>
<Text style={styles.listHeader}>{item.header}</Text>
<Text style={styles.listValue}>{item.value}</Text>
</View>
</View>
<Image
style={styles.listimgArrow}
source={require("../../resources/toolbar/chevron_right_grey.png")}
/>
</View>
</TouchableWithoutFeedback>
);
};
// Render callBack
render() {
const { stBool } = this.state;
const navigationOptions = ({ navigation }) => ({
title: i18n.t("atmbranchpickHeader"),
headerRight: stBool ? (
<TouchableHighlight
onPress={() => {
navigation.navigate("home");
}}
>
<Image
style={{ marginRight: 20 }}
source={require("../../resources/toolbar/home_white.png")}
/>
</TouchableHighlight>
) : null,
headerTintColor: "white",
headerStyle: {
backgroundColor: colors.themeColor
// top: 30
}
});
return (
<View style={styles.mainWrapper}>
<FlatList data={this.state.data} renderItem={this._renderList} />
</View>
);
}
}

Related

How to use auto scroll view in react native with dote?

here is my code
App.js
import React from 'react'
import { Image, StyleSheet, TouchableOpacity, Dimensions, Text, View } from 'react-native'
import { scale, verticalScale } from "react-native-size-matters"
import { RFPercentage} from 'react-native-responsive-fontsize';
import { FlatList } from 'react-native';
const dummyData =
[{
title: 'Get instant loans with approvals',
uri: 'https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcTWo3YRChZ3ADpZ7rEfQu1RvBOu9NMWZIMZBaH-a1CArXqx6nLX',//require('../img/1page.jpg'),
id: 1
},
// {
// title: 'Get money in wallet or bank account',
// uri: 'https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcQN0NcV2epN147CiVfr_VAwsbU3VO8rJU0BPphfU9CEsVWa-kRX',//require('../img/1page.jpg'),
// id: 2
// },
// {
// title: 'Refer & earn exciting gifts',
// uri: 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSUbS4LNT8rnIRASXO6LGFSle7Mhy2bSLwnOeqDMivYTb2cgTJg',//require('../img/1page.jpg'),
// id: 3
// }
]
const Home = ({ navigation }) => {
const renderItem=({item})=>{
return(
<View>
<Image source={{uri:item.uri}}style={styles.img} />
<View style={styles.dotView}>
<View style={styles.dot}/>
<View style={styles.dot}/>
<View style={styles.dot}/>
</View>
<Text style={styles.text}>{item.title}</Text>
</View>
)
}
return (
<View style={styles.contanier}>
<View style={styles.imgView}>
<Image source={require('../img/homelogo.png')} style={styles.logo} />
</View>
<View style={{marginBottom:8}}>
<FlatList
data={dummyData}
renderItem={renderItem}
keyExtractor={item => item.id}
/>
</View>
<View style={styles.btnview}>
<TouchableOpacity style={styles.btn}
onPress={() => navigation.navigate("PermissionPage")}
>
<Text style={styles.btntext}>Get Started</Text>
</TouchableOpacity>
</View>
</View>
)
}
export default Home;
const styles = StyleSheet.create({
contanier: {
flex: 1,
backgroundColor: '#fff',
},
imgView: {
marginTop: verticalScale(10),
marginLeft: 20,
},
logo: {
width: scale(70),
height: verticalScale(70),
borderRadius: 50,
// position: 'absolute'
},
btnview: {
alignItems: 'center',
justifyContent: 'center',
marginTop:10,
},
btn: {
width: scale(250),
height: verticalScale(55),
borderRadius: 5,
backgroundColor: '#2192FF',
alignItems: 'center',
justifyContent: 'center',
},
btntext: {
fontSize: RFPercentage(3.20),// fontSize: RFValue(17, 680),
color: '#fff',
fontWeight: '600',
fontFamily: 'Roboto'
},
img:{
width:scale(300),
height:verticalScale(450),
},
text:{
fontSize:RFPercentage(3),
fontWeight:'bold',
color:'#000',
textAlign:'center'
},
dotView:{
flexDirection:'row',
justifyContent:'center',
marginBottom:8
},
dot:{
width:scale(8),
height:verticalScale(8),
backgroundColor:'#2192ff',
borderRadius:20,
marginLeft:5
}
})
here is output I want
https://imgur.com/a/yvR5XgM
I'm creating new app in app home page have auto scroll img but I don't know how to use it and do it
I'm fine some lib but i don't use any lib I want without lib.
I'm seen may qustion on internet but I'm not find soution what I want
any one can help me ?

CustomDrawerNavigator: Change Active and Inactive Background Colour

On react-navigation/drawer's DrawerItem, is there a way to add active and inactive background colour? I followed this document to implement this https://reactnavigation.org/docs/drawer-navigator/.
I have added theses code lines to the drawerItems. But it won't work for me.
drawerContentOptions={{
activeTintColor: '#fff', /* font color for active screen label */
activeBackgroundColor: '#68f', /* bg color for active screen */
inactiveTintColor: 'grey', /* Font color for inactive screens' labels */
}}
initialized by the following,
import * as React from 'react';
import {
Button,
View,
Text,
StyleSheet,
TouchableOpacity,
Image,
} from 'react-native';
import { useDispatch, useSelector } from 'react-redux';
import {
createDrawerNavigator,
DrawerContentScrollView,
DrawerItem,
} from '#react-navigation/drawer';
import Home from '../home/containers';
import NavigationService from '../../navigation/NavigationService';
import * as homeActions from '../../features/home/actions';
import * as loginActions from '../../features/login/actions';
import { Images } from '../../config';
import i18n from 'i18n-js';
function HomeScreen({ navigation }) {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Button
onPress={() => NavigationService.navigate('Notifications')}
title="Go to notifications"
/>
</View>
);
}
function NotificationsScreen({ navigation }) {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Button onPress={() => NavigationService.goBack()} title="Go back home" />
</View>
);
}
function CustomDrawerContent({ props, navigation }) {
const dispatch = useDispatch();
const outlets = useSelector((state) => state.homeReducer.outlets);
const defaultOutLet = useSelector((state) => state.homeReducer.defaultOutLet);
const drawerItems = outlets.map((outlet) => {
return (
console.log("############## nav drawr ################## " + outlet.name),
<DrawerItem
{...props}
key={outlet.userCompanyId}
label={outlet.name}
onPress={() => {
dispatch(homeActions.changeSelectedOutlet(outlet));
navigation.closeDrawer();
}}
/>
);
});
return (
<View style={styles.flexView}>
<View style={styles.container}>
<Image
style={styles.image}
source={Images.icons.logo}
resizeMode="contain"
/>
{defaultOutLet && <Text style={styles.text}>{defaultOutLet.name}</Text>}
</View>
<View style={styles.separator} />
<View style={styles.flexView}>{drawerItems}</View>
<View style={styles.separator} />
<View style={styles.bottomView}>
<TouchableOpacity
style={styles.logoutContainer}
onPress={() => {
dispatch(homeActions.clearUserCompany());
dispatch(loginActions.completeLogOutClearingUserData());
}}>
<Image
style={styles.logoutIcon}
source={Images.icons.power}
resizeMode="center"
/>
<Text style={styles.logoutText}>{i18n.t('common.logout')}</Text>
</TouchableOpacity>
</View>
</View>
);
}
const Drawer = createDrawerNavigator();
export default function DrawerNavigator() {
return (
<Drawer.Navigator
drawerContent={(props) => <CustomDrawerContent {...props} />}
initialRouteName="Home">
<Drawer.Screen name="Home" component={Home} />
</Drawer.Navigator>
);
}
const styles = StyleSheet.create({
container: {
flex: 0.3,
width: '100%',
backgroundColor: 'white',
},
flexView: {
flex: 1,
},
text: {
marginVertical: 12,
color: 'black',
textAlign: 'center',
},
logoutContainer: {
flexDirection: 'row',
alignItems: 'center',
width: '100%',
},
logoutText: {
color: 'gray',
},
logoutIcon: {
flex: 0.4,
},
image: {
flex: 1,
marginTop: 20,
alignSelf: 'center',
},
separator: {
width: '100%',
height: 1,
backgroundColor: 'gray',
},
bottomView: {
flex: 0.15,
width: '100%',
justifyContent: 'center',
},
});

Fetching data from URL works in ReactJS but does not work in Native

Fetching data from URL by search it, it works in React and not working in React Native how to solve the problem?
import React, { Component } from 'react'
import { SafeAreaView, StyleSheet, StatusBar, ScrollView, View, Text, TextInput, Button } from 'react-native';
import axios from 'axios';
export default class Main extends Component {
constructor(props){
super(props)
this.state={
ifscCode:"",
detail:{}
}
}
ifscSearch = () => {
const that = this;
axios.get('https://ifsc.razorpay.com/${this.state.ifscCode}')
.then(function (response) {
if (response.status == 200){
that.setState({detail:response.data})
console.log(data);
}
})
.catch(function (error) {
console.log(error);
})
}
ifscCodeChange = (Value) => {
this.setState({ifscCode:Value})
}
render() {
return (
<>
<StatusBar barStyle="light-content" />
<SafeAreaView>
<ScrollView>
<View style={styles.maincnt}>
<View style={styles.inpcnt}>
<NewIfsc ifscCodeChange={this.ifscCodeChange} />
</View>
<View style={styles.btncnt}>
<Button title='Search' style={styles.btn} onClick={this.ifscSearch} />
</View>
<View style={styles.listcnt}>
<Text>BANK: {this.state.detail.BANK}</Text>
<Text>{this.state.detail.BRANCH}</Text>
<Text>{this.state.detail.STATE}</Text>
<Text>{this.state.detail.CONTACT}</Text>
<Text>{this.state.detail.ADDRESS}</Text>
<Text>{this.state.detail.BANKCODE}</Text>
<Text>{this.state.detail.DISTRICT}</Text>
<Text>{this.state.detail.STATE}</Text>
<Text>{this.state.detail.IFSC}</Text>
</View>
</View>
</ScrollView>
</SafeAreaView>
</>
)
}
}
class NewIfsc extends Component {
render() {
return (
<View style={styles.inpcnt}>
<TextInput style={styles.txtinp} maxLength={11} placeholder='ifsc code search' onChange={(e)=>this.props.ifscCodeChange(e.target.Value)} />
</View>
)
}
}
const styles = StyleSheet.create({
maincnt:{
flex:1,
margin: 10,
backgroundColor: 'white'
},
inpcnt:{
marginTop: 20,
},
btncnt:{
marginTop: 20,
},
listcnt:{
marginTop: 20
},
txtinp:{
width: 350,
height: 50,
borderRadius: 25,
borderWidth: 2,
borderColor: 'indigo',
alignSelf: 'center',
padding: 10
},
btn:{
width: 100,
height: 70,
alignSelf: 'center'
},
listcnt:{
marginTop: 50,
alignContent: 'center',
justifyContent: 'center'
}
});

How to update data in first component when added data in another component

I have two components with realm database one is for listing and other is for adding data. But my problem is that i can't update list when data is adding into second component. I have tried App state listener also but it's not triggering when user come at first screen.
This is list component
import React, { Component } from "react";
import AppScreen from "../AppScreen.js";
import realm from "../databases/RealmController.js";
import colors from "../Ui/colors.js";
import Swipeout from "react-native-swipeout";
import { Icon } from "react-native-vector-icons";
import { NavigationActions } from "react-navigation";
import Dash from "react-native-dash";
import AppStateListener from "react-native-appstate-listener";
import {
AppState,
AppRegistry,
StyleSheet,
Text,
Image,
Button,
View,
FlatList,
TouchableHighlight,
TouchableOpacity,
Alert,
StatusBar,
TextInput
} from "react-native";
type Props = {};
export default class ReminderList extends Component<Props> {
state = {
data: [],
loading: true,
refresh: false,
appState: AppState.currentState
};
static navigationOptions = {
header: null,
title: " List"
};
handleActive() {
console.warn("The application is now active!");
}
handleBackground() {
console.warn("The application is now in the background!");
}
handleInactive() {
console.warn("The application is now inactive!");
}
componentDidMount() {
//this.fetchData();
AppState.addEventListener("change", this.handleAppStateChange);
}
componentWillUnmount() {
AppState.removeEventListener("change", this.handleAppStateChange);
}
gotoAddReminder = () => {
// handle navigation
this.props.screenProps.rootNavigation.navigate("addReminder");
};
handleAppStateChange = nextAppState => {
if (nextAppState === "active") {
this.setState({ data: null });
this.fetchData();
this.setState({ refresh: true });
// console.warn("hello i active");
//this.flatList.scrollToIndex({ animated: true, index: 0 });
}
else {
this.setState({ refresh: false });
// console.warn("hello i inactive");
}
this.setState({ appState: nextAppState });
};
fetchData() {
let reminderList = realm.objects("Reminder");
this.setState({ data: reminderList });
}
renderClientRow(item) {
return (
<TouchableHighlight underlayColor="rgba(192,192,192,1,0.6)">
<View style={styles.cardView}>
<View style={styles.dateView}>
<Text style={styles.dateText}>18</Text>
<Text style={styles.monthText}>Jan</Text>
</View>
<View
style={{
width: 1,
backgroundColor: colors.darkGray,
marginLeft: 15,
marginRight: 20
}}
/>
<View style={{ flexDirection: "row", marginTop: 15, width: "100%" }}>
<View style={{ flexDirection: "column" }}>
<Text style={styles.titleText}>{item.name}</Text>
<Text style={(styles.item, { marginTop: 5 })}>location</Text>
<Dash
style={{
width: 300,
marginTop: 10,
height: 1,
marginRight: 15
}}
/>
<View
style={{
flex: 1,
flexDirection: "row",
marginTop: 5,
marginBottom: 15
}}
>
<Image
style={{
width: 15,
height: 15,
marginTop: 5,
marginRight: 10
}}
source={require("../Image/ic_date.png")}
/>
<Text style={styles.item}>0.40 pm</Text>
</View>
</View>
</View>
</View>
</TouchableHighlight>
);
}
render() {
return (
<View style={styles.container}>
<AppStateListener
onActive={this.handleActive}
onBackground={this.handleBackground}
onInactive={this.handleInactive}
/>
<FlatList
ref={(c) => { this.flatList = c }}
data={this.state.data}
extraData={this.state.refresh}
renderItem={({ item }) => this.renderClientRow(item)}
keyExtractor={item => item.id}
/>
<TouchableOpacity
activeOpacity={0.5}
onPress={() => {
this.gotoAddReminder();
}}
style={styles.TouchableOpacityStyle}
>
<Image
source={{
uri:
"https://reactnativecode.com/wp-content/uploads/2017/11/Floating_Button.png"
}}
style={styles.FloatingButtonStyle}
/>
</TouchableOpacity>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
paddingTop: 0
},
MainContainer: {
justifyContent: "center",
flex: 1,
margin: 10
},
TouchableOpacityStyle: {
position: "absolute",
width: 50,
height: 50,
alignItems: "center",
justifyContent: "center",
right: 30,
bottom: 30
},
FloatingButtonStyle: {
resizeMode: "contain",
width: 50,
height: 50
},
cardView: {
backgroundColor: "#fff",
borderWidth: 0.5,
paddingLeft: 15,
paddingRight: 10,
marginLeft: 10,
marginTop: 10,
marginRight: 10,
borderRadius: 5,
flexDirection: "row"
},
item: {
fontSize: 16,
color: colors.darkGray
},
itemRight: {
fontSize: 18,
textAlign: "right"
},
titleText: {
fontSize: 20,
color: "black",
fontWeight: "400"
},
dateText: {
fontSize: 32,
color: colors.appColor,
fontWeight: "500"
},
monthText: {
fontSize: 22,
color: colors.appColor,
fontWeight: "500"
},
dateView: {
alignItems: "center",
justifyContent: "center",
flexDirection: "column",
marginLeft: 15,
marginRight: 15,
marginTop: 15,
marginBottom: 15
},
rightText: {
fontSize: 22,
color: "black",
textAlign: "right",
fontWeight: "bold"
},
myStarStyle: {
color: "yellow",
backgroundColor: "transparent",
textShadowColor: "black",
textShadowOffset: { width: 1, height: 1 },
textShadowRadius: 2
},
myEmptyStarStyle: {
color: "white"
}
});
This is AddData component
import React, { Component } from "react";
import realm from "../databases/RealmController.js";
import styles from "../Ui/AddClientStyles.js";
import { TextInputLayout } from "rn-textinputlayout";
import DatePicker from "react-native-datepicker";
import {
AppRegistry,
StyleSheet,
Text,
TouchableHighlight,
Button,
View,
ScrollView,
Image,
Alert,
StatusBar,
TextInput
} from "react-native";
const EMAIL_REGEX = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
type Props = {};
export default class AddReminder extends Component<Props> {
state = {
to: "",
from: "",
name: "",
note: "",
location: ""
};
handlePress = async () => {
var Id = realm.objects("Reminder").length + 1;
realm.write(() => {
realm.create("Reminder", {
id: Id,
name: this.state.name,
note: this.state.note,
location: this.state.location,
to: this.state.to,
from: this.state.from
});
});
this.props.navigation.goBack();
};
render() {
return (
<ScrollView style={styles.container}>
<View style={styles.container}>
<View style={styles.profileContainer} />
<View style={styles.bottomContainer}>
<Text style={[styles.titleText, styles.titleStyle]}>
Basic Information
</Text>
<TextInputLayout style={{ marginTop: 0 }}>
<TextInput
style={styles.textInput}
placeholder={"Reminder Title"}
onChangeText={text => this.setState({ name: text })}
/>
</TextInputLayout>
<TextInputLayout style={styles.inputLayout}>
<TextInput
style={styles.textInput}
placeholder={"Note"}
onChangeText={text => this.setState({ note: text })}
/>
</TextInputLayout>
<TextInputLayout style={styles.inputLayout}>
<TextInput
style={styles.textInput}
placeholder={"Location"}
onChangeText={text => this.setState({ location: text })}
/>
</TextInputLayout>
<Text style={[styles.titleText, styles.titleStyle]}>
Date & Time
</Text>
<View style={styles.dateToContainer}>
<View style={{ flexDirection: "column", width: "30%" }}>
<Text style={styles.textInput}>From</Text>
</View>
<View styles={{ flexDirection: "column", width: "70%" }}>
<DatePicker
style={{ width: 200 }}
date={this.state.from}
mode="datetime"
format="YYYY-MM-DD HH:mm"
confirmBtnText="Confirm"
cancelBtnText="Cancel"
customStyles={{
dateIcon: {
position: "absolute",
left: 0,
top: 4,
marginLeft: 0
},
dateInput: {
marginLeft: 36
}
}}
minuteInterval={10}
onDateChange={datetime => {
this.setState({ from: datetime });
}}
/>
</View>
</View>
<View style={styles.dateContainer}>
<View style={{ flexDirection: "column", width: "30%" }}>
<Text style={styles.textInput}>To</Text>
</View>
<View styles={{ flexDirection: "column", width: "70%" }}>
<DatePicker
style={{ width: 200 }}
date={this.state.to}
mode="datetime"
format="YYYY-MM-DD HH:mm"
confirmBtnText="Confirm"
cancelBtnText="Cancel"
customStyles={{
dateIcon: {
position: "absolute",
left: 0,
top: 4,
marginLeft: 0
},
dateInput: {
marginLeft: 36
}
}}
minuteInterval={10}
onDateChange={datetime => {
this.setState({ to: datetime });
}}
/>
</View>
</View>
<TouchableHighlight
style={styles.btnStyle}
onPress={() => {
this.handlePress();
}}
underlayColor="#fff"
>
<Text style={styles.btnText}>Add Reminder</Text>
</TouchableHighlight>
<TouchableHighlight
style={{marginTop:20}}>
<Text/>
</TouchableHighlight>
</View>
</View>
</ScrollView>
);
}
}
When u use this.props.navigation.goBack(); those components not render again or not call any method that component so can use this.props.navigation.navigate('your_route_path');

React-Native ListView with Object Array

Hey all would love some help will this question.. I have been tearing my hair out!
I'm trying to render a ListView using an array of objects of the form:
Array[number]
0: Object
category: ''
date: ''
total: ''
vendor: ''
1: Object ..etc.
I am using the component react-native-swipe-list-view found here: swipeList github
But I'm only rendering the last element of my array of data objects! I'm also using redux in this react-native application although I don't see this having any effect
HELP ! :)
Output is as follows
Here is my current code.
import React, {
Component,
} from 'react';
import {
ListView,
Text,
TouchableOpacity,
TouchableHighlight,
View,
Alert
} from 'react-native';
import { connect } from 'react-redux';
import { Actions } from 'react-native-router-flux';
import { SwipeListView } from 'react-native-swipe-list-view';
import {
PRIMARY_HIGHLIGHT_COLOUR,
CARD_BACKGROUND_COLOUR,
BORDER_COLOUR
} from '../global/colours';
import {
MySearchBar,
Button,
FAB,
BackgroundView,
} from '../components';
import { HEADER } from '../global/margins';
class ReceiptsListView extends Component {
constructor(props) {
super(props);
console.log(this.props.receiptList);
this.ds = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 });
this.state = {
listViewData: this.ds.cloneWithRows(this.props.receiptList)
};
console.log('state', this.state);
}
/* shouldComponentUpdate(nextProps) {
if (this.props !== nextProps) {
return true;
}
return false;
} */
deleteRow(secId, rowId, rowMap) {
// rowMap[`${secId}${rowId}`].closeRow();
//console.log('delete', secId, rowId, rowMap);
// const newData = [...this.state.listViewData];
// newData.splice(rowId, 1);
// this.setState({ listViewData: newData });
}
render() {
//const ds = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 });
//const dataSource = ds.cloneWithRows(receiptlist);
//this.ds = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 });
return (
<BackgroundView style={styles.container}>
<View style={styles.search}>
<MySearchBar />
<Button style={styles.button}> Export </Button>
</View>
<SwipeListView
dataSource={this.state.listViewData}
renderRow={(data) => this.renderRow(data)}
renderHiddenRow={(secId, rowId, rowMap) => this.renderHiddenRow(secId, rowId, rowMap)}
rightOpenValue={-150}
recalculateHiddenLayout
previewFirstRow
/>
<FAB
onPress={this.onPressFAB}
/>
</BackgroundView>
);
}
renderRow(data) {
console.log('data', data);
return (
<TouchableHighlight
onPress={console.log('You touched me')}
style={styles.rowFront}
underlayColor={'#AAA'}
>
<View>
<View style={{ flexDirection: 'row', justifyContent: 'space-between' }} >
<Text> {`${data.vendor}`} </Text>
<Text> {`${data.total}`} </Text>
</View>
<View>
<Text> {`${data.date}`} </Text>
<Text> {`${data.category}`} </Text>
</View>
</View>
</TouchableHighlight>
);
}
renderHiddenRow(secId, rowId, rowMap) {
return (
<View style={styles.rowBack}>
<TouchableOpacity
style={[styles.backRightBtn, styles.backRightBtnLeft]}
onPress={_ => (console.log(secId, rowId, rowMap))}
>
<Text style={styles.backTextWhite}>Export</Text>
</TouchableOpacity>
<TouchableOpacity
style={[styles.backRightBtn, styles.backRightBtnRight]}
onPress={_ => (console.log(secId, rowId, rowMap))}
>
<Text style={styles.backTextWhite}>Delete</Text>
</TouchableOpacity>
</View>
);
}
onPressFAB() {
console.log('FAB pressed');
Alert.alert(
'Choose Photo Source',
null,
[
{ text: 'Camera', onPress: () => Actions.camera() },
{ text: 'Photo Library', onPress: () => Actions.photos() },
{ text: 'Cancel', onPress: () => console.log('cancel'), style: 'cancel' }
]
);
}
}
const styles = {
search: {
flexDirection: 'row',
padding: 10,
height: 60,
backgroundColor: PRIMARY_HIGHLIGHT_COLOUR
},
button: {
marginTop: 0,
height: 30,
flexGrow: 0.3
},
container: {
padding: 0,
paddingTop: HEADER.height
},
rowFront: {
//alignItems: 'center',
flex: 1,
padding: 10,
backgroundColor: CARD_BACKGROUND_COLOUR,
borderBottomColor: BORDER_COLOUR,
borderBottomWidth: 1,
justifyContent: 'center',
//height: 100,
},
rowBack: {
alignItems: 'center',
backgroundColor: '#DDD',
flex: 1,
flexDirection: 'row',
justifyContent: 'space-between',
paddingLeft: 15,
},
backRightBtn: {
alignItems: 'center',
bottom: 0,
justifyContent: 'center',
position: 'absolute',
top: 0,
width: 75
},
backRightBtnLeft: {
backgroundColor: 'blue',
right: 75
},
backRightBtnRight: {
backgroundColor: 'red',
right: 0
},
controls: {
alignItems: 'center',
marginBottom: 30
},
switchContainer: {
flexDirection: 'row',
justifyContent: 'center',
marginBottom: 5
},
switch: {
alignItems: 'center',
borderWidth: 1,
borderColor: 'black',
paddingVertical: 10,
width: 100,
}
};
const mapStateToProps = ({ receipts, accounts }) => {
const {
myReceipts,
receiptList
} = receipts;
const {
labelsArray
} = accounts;
return {
myReceipts,
receiptList,
labelsArray
};
};
export default connect(mapStateToProps, {
})(ReceiptsListView);
the issue was the flex:1 in styling of the renderRow (styles.
rowFront)
Below is the working code as I'm sure it can be helpful to others.
import React, {
Component,
} from 'react';
import {
ListView,
Text,
TouchableOpacity,
TouchableHighlight,
View,
Alert,
TextInput
} from 'react-native';
import { connect } from 'react-redux';
import { Actions } from 'react-native-router-flux';
import { SwipeListView } from 'react-native-swipe-list-view';
import Icon from 'react-native-vector-icons/FontAwesome';
import Spinner from 'react-native-loading-spinner-overlay';
import {
PRIMARY_HIGHLIGHT_COLOUR,
CARD_BACKGROUND_COLOUR,
BORDER_COLOUR,
SHADOW_COLOUR
} from '../global/colours';
import {
Button,
FAB,
BackgroundView,
TitleText
} from '../components';
import { HEADER } from '../global/margins';
import { searchTextChanged, deleteReceipt } from '../actions';
class ReceiptsListView extends Component {
constructor(props) {
super(props);
console.log(this.props.receiptList);
console.log(this.props.categories);
this.ds = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 });
}
shouldComponentUpdate(nextProps) {
if (this.props !== nextProps) {
return true;
} else if (this.props.searchQuery !== nextProps.searchQuery) {
return true;
}
return false;
}
render() {
if (this.props.receiptList.length < 1) {
return (
<BackgroundView style={styles.emptyContainer}>
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<TitleText> No Receipts </TitleText>
</View>
<FAB
onPress={this.onPressFAB}
/>
</BackgroundView>
);
}
return (
<BackgroundView style={styles.container}>
<View style={styles.search}>
<View style={{ flexGrow: 1, height: 35, paddingTop: 5 }}>
<View style={styles.searchStyle}>
<View style={styles.searchbar}>
<Icon
name="search"
size={15}
color="#ddd"
/>
<TextInput
style={{ flexGrow: 1, width: null, paddingLeft: 5 }}
placeholder='search'
placeholderTextColor='lightgray'
onChangeText={this.onSearchChange.bind(this)}
value={this.props.searchQuery}
onFocus={() => console.log('hi')}
/>
</View>
</View>
</View>
<Button
style={styles.button}
//onPress={this.searchText()}
>
Search
</Button>
</View>
<SwipeListView
dataSource={this.ds.cloneWithRows(this.props.receiptList)}
renderRow={(data) => this.renderRow(data)}
renderHiddenRow={(secId, rowId, rowMap) => this.renderHiddenRow(secId, rowId, rowMap)}
rightOpenValue={-150}
recalculateHiddenLayout
previewFirstRow
/>
<FAB
onPress={this.onPressFAB}
/>
<Spinner
visible={this.props.isFetching}
textContent={''}
textStyle={{ color: 'white' }}
/>
</BackgroundView>
);
}
onSearchChange(text) {
this.props.searchTextChanged(text);
}
renderRow(data) {
//console.log('data', data);
return (
<TouchableHighlight
onPress={() => console.log('You touched me', data)}
underlayColor={'#AAA'}
style={styles.rowFront}
>
<View>
<View style={{ flexDirection: 'row', justifyContent: 'space-between' }} >
<Text> {`${data.vendor}`} </Text>
<Text> {`${data.total}`} </Text>
</View>
<View>
<Text> {`${data.date}`} </Text>
<Text> {`${data.category}`} </Text>
</View>
</View>
</TouchableHighlight>
);
}
renderHiddenRow(secId, rowId, rowMap) {
return (
<View style={styles.rowBack}>
<TouchableOpacity
style={[styles.backRightBtn, styles.backRightBtnLeft]}
onPress={() => (this.exportItem(secId, rowId, rowMap))}
>
<Text style={styles.backTextWhite}>Export</Text>
</TouchableOpacity>
<TouchableOpacity
style={[styles.backRightBtn, styles.backRightBtnRight]}
onPress={() => (this.deleteItem(secId, rowId, rowMap))}
>
<Text style={styles.backTextWhite}>Delete</Text>
</TouchableOpacity>
</View>
);
}
deleteItem(secId, rowId, rowMap) {
console.log('secId', secId, 'rowId', rowId, 'rowMap', rowMap);
console.log('obj', secId.id, 'acc', this.props.curAccountID);
this.props.deleteReceipt(this.props.curAccountID, secId.id);
}
exportItem(secId, rowId, rowMap) {
console.log('secId', secId, 'rowId', rowId, 'rowMap', rowMap);
//this.props.exportReceipt(this.props.curAccountID, secId.id);
}
onPressFAB() {
console.log('FAB pressed');
Alert.alert(
'Choose Photo Source',
null,
[
{ text: 'Camera', onPress: () => Actions.camera() },
{ text: 'Photo Library', onPress: () => Actions.photos() },
{ text: 'Cancel', onPress: () => console.log('cancel'), style: 'cancel' }
]
);
}
}
const styles = {
search: {
flexDirection: 'row',
padding: 10,
height: 60,
backgroundColor: PRIMARY_HIGHLIGHT_COLOUR
},
searchbar: {
flex: 1,
flexDirection: 'row',
justifyContent: 'space-between',
paddingLeft: 5
},
button: {
marginTop: 0,
height: 30,
flexGrow: 0.3
},
container: {
padding: 0,
paddingTop: HEADER.height
},
emptyContainer: {
flex: 1,
padding: 0,
paddingTop: HEADER.height,
justifyContent: 'center'
},
rowFront: {
//alignItems: 'center',
padding: 10,
backgroundColor: CARD_BACKGROUND_COLOUR,
borderBottomColor: BORDER_COLOUR,
borderBottomWidth: 1,
justifyContent: 'center',
//height: 100,
},
rowBack: {
alignItems: 'center',
backgroundColor: '#DDD',
flex: 1,
flexDirection: 'row',
justifyContent: 'space-between',
paddingLeft: 15,
},
backRightBtn: {
alignItems: 'center',
bottom: 0,
justifyContent: 'center',
position: 'absolute',
top: 0,
width: 75
},
backRightBtnLeft: {
backgroundColor: 'blue',
right: 75
},
backRightBtnRight: {
backgroundColor: 'red',
right: 0
},
controls: {
alignItems: 'center',
marginBottom: 30
},
switchContainer: {
flexDirection: 'row',
justifyContent: 'center',
marginBottom: 5
},
switch: {
alignItems: 'center',
borderWidth: 1,
borderColor: 'black',
paddingVertical: 10,
width: 100,
},
searchStyle: {
flex: 1,
flexDirection: 'row',
alignSelf: 'stretch',
padding: 5,
justifyContent: 'flex-start',
alignItems: 'center',
backgroundColor: CARD_BACKGROUND_COLOUR,
borderRadius: 10,
borderWidth: 1,
borderColor: 'grey',
marginLeft: 5,
marginRight: 5,
shadowColor: SHADOW_COLOUR,
shadowOffset: { width: 0, height: 2 },
shadowOpacity: 0.1,
shadowRadius: 2,
},
};
const mapStateToProps = ({ accounts, receipts, searchIt }) => {
const {
curAccountID
} = accounts;
const {
searchQuery
} = searchIt;
const {
isFetching,
myReceipts,
receiptList,
categories
} = receipts;
return {
curAccountID,
isFetching,
myReceipts,
receiptList,
searchQuery,
categories
};
};
export default connect(mapStateToProps, {
searchTextChanged, deleteReceipt
})(ReceiptsListView);

Resources