How to use for Loop in react native - react-native

I am new to react native I want to use for loop for showing multiple data. which is come from previous screen from API.
here is my code. I want to show full view in return in for loop multiple times. I am getting data in this => this.props.route.params.data[i].lead_tag_number
const { width } = Dimensions.get("window");
class Browse extends Component {
constructor(props) {
super(props);
this.state ={
Email:"",
}
this.handleBackButtonClick = this.handleBackButtonClick.bind(this);
}
componentDidMount() {
BackHandler.addEventListener('hardwareBackPress', this.handleBackButtonClick);
}
componentWillUnmount() {
BackHandler.removeEventListener('hardwareBackPress', this.handleBackButtonClick);
}
handleBackButtonClick() {
this.props.navigation.navigate("Browse");
return true;
}
render() {
const { profile, navigation } = this.props;
const tabs = [""];
const route = this.props
return (
<View style={{alignItems:"center", justifyContent:"center",height:140, width:"90%", marginTop:30}}>
<TouchableOpacity onPress={() => navigation.navigate("FormItems")}>
<Card center middle shadow style={{ height:80, width:"100%" }} >
<Text medium height={15} size={14}style={{ fontWeight: "bold", paddingRight:190}}>
{this.props.route.params.data[i].lead_tag_number}
</Text>
</Card>
</TouchableOpacity>
</View>
);
}
}

Did you try this?
...
this.props.route.params.data[i].lead_tag_number.map((item, i){
<TAG key={i} />
});
...

Related

React Native Cannot update during an existing state transition (such as within `render`). Render methods should be a pure function of props and state

Im learning react native, and i try to use state, now im facing an issue "Cannot update during an existing state transition (such as within render). Render methods should be a pure function of props and state."
Here my code
class Quantity extends React.Component {
constructor(props) {
super(props);
this.state = {
qty:1
};
this.setQty = this.setQty.bind(this);
}
setQty = (e) =>{
this.setState({
qty:e,
});
}
componentDidMount() {
this.props.onRef(this)
this.state.qty = 1
}
componentWillUnmount() {
this.props.onRef(undefined)
}
getCheckoutQty() {
return this.state.qty.toString();
}
minusQty = () => {
let newQty = this.state.qty -1;
this.setQty(newQty)
}
plusQty = () => {
let newQty = this.state.qty +1;
this.setQty(newQty);
}
render() {
const {qty}=this.state
return (
<View style={styles.row}>
<TouchableOpacity style={styles.icon}
disabled={(this.state.qty==1)?true:false}
// onPress={() => this.minusQty()}
>
<Icon name="minus" color="#000" style={(this.state.qty==1)?{opacity:0.2}:{opacity:1}}/>
</TouchableOpacity>
<Input
style={styles.qtyBox}
keyboardType="numeric"
returnKeyType="done"
value={qty.toString()}
onChangeText={(e)=>this.setQty(this)}
/>
<TouchableOpacity style={styles.icon}
// onPress={() => this.plusQty()}
>
<Icon name="plus" color="#000" />
</TouchableOpacity>
</View>
);
}
}
any way to fix it?
Thank for the support

Back button to correct position of flatlist

I have a flatlist with many product . E.g. I click lot 20, it will proceed to screen with product detail. In product detail screen have a search function to other product. If search for lot 1 it will show product detail for lot 1. But when click back button it show the flatlist screen at the position of product 20, I want it to show the flatlist screen at the position of product 1. I am using react native class component. Can someone help?
flatlist.js
class FlatlistScreen extends React.Component {
constructor(props) {
super(props);
this.state = {
};
}
componentDidMount(){
}
render(){
return(
<SafeAreaView style={{flex: 1}}>
<AnimatedFlatList
style={{flex: 1}}
ref={(ref) => this.flatListRef = ref}
data={this.props.APIE}
renderItem={this.renderItem}
contentContainerStyle={{paddingTop: Platform.OS !== 'ios' ? HEADER_MAX_HEIGHT : 0,}}
keyExtractor={item => item._id}
refreshing={this.state.refreshing}
removeClippedSubviews={Platform.OS == "android" ? this.state.sticky.length > 0 : true}
scrollEventThrottle={1}
refreshControl={
<RefreshControl
refreshing={this.state.refreshing}
onRefresh={
this.onRefresh.bind(this)
}
progressViewOffset={HEADER_MAX_HEIGHT}
/>
}
contentInset={{
top: HEADER_MAX_HEIGHT,
}}
contentOffset={{
y: -HEADER_MAX_HEIGHT,
}}
onScroll={Animated.event(
[{ nativeEvent: { contentOffset: { y: this.state.scrollY } } }],
{ useNativeDriver: true },
)}
/>
</SafeAreaView>
)
}
}
productDetail.js
class ProductDetailScreen extends React.Component {
constructor(props) {
super(props);
this.state = {
};
}
componentDidMount(){
BackHandler.addEventListener('hardwareBackPress', this.handleBackButtonClick);
}
handleBackButtonClick() {
return true;
}
render(){
return(
<Text>Product Detail</Text>
)
}
}
On this.renderItem you probably use ProductDetailScreen to render this.props.APIE elements. Well, you could add a prop to ProductDetailScreen like:
<ProductDetailScreen onGoBack={this.scrollToTop} /*other props*/ />
this.scrollToTop looks like:
scrollToTop() {
this.flatListRef.scrollToOffset({ animated: true, offset: 0 });
}
So this is the function that scoll the Flatlist to top.
Ok, now on ProductDetailScreen component, when we go back (I mean, on handleBackButtonClick function) we can call props.onGoBack():
class ProductDetailScreen extends React.Component {
...
handleBackButtonClick() {
props.onGoBack();
return true;
}
...
}
Thats it. Now when you go back from product details, FlatList will scroll to top.

How to pass state between screens in React Native

This is screen 1, where I am supposed to be passing the state for button text.
export class EditProfile extends Component {
constructor(props) {
super(props);
this.navigateToName = this.navigateToName.bind(this);
this.navigateToAboutMe = this.navigateToAboutMe.bind(this);
this.navigateToInterests = this.navigateToInterests.bind(this);
this.state = {
showing: true,
aboutUser: {
buttonText: "hey",
showing: false,
},
};
}
navigateToName = () => {
this.props.navigation.navigate("CreateProfile", {
showing: false,
});
};
navigateToAboutMe = () => {
this.props.navigation.navigate("AboutUser", {
aboutUser: this.state.aboutUser,
});
};
navigateToInterests = () => {
this.props.navigation.navigate("Interests", { showing: false });
};
render() {
return (
<View>
<View style={ProfileEditStyle.justifyImage}>
<Image
style={ProfileEditStyle.image}
source={require("../../Graphics/jessica_alba.jpg")}
/>
</View>
<View>
<Text style={ProfileEditStyle.basictext}>Basic Info</Text>
<TouchableOpacity style={ProfileEditStyle.buttons}>
<Text style={ProfileEditStyle.text} onPress={this.navigateToName}>
Edit Name
</Text>
</TouchableOpacity>
<TouchableOpacity style={ProfileEditStyle.buttons}>
<Text style={ProfileEditStyle.text}>Edit Photo</Text>
</TouchableOpacity>
<TouchableOpacity style={ProfileEditStyle.buttons}>
<Text style={ProfileEditStyle.text}>Edit Location</Text>
</TouchableOpacity>
<TouchableOpacity
style={ProfileEditStyle.buttons}
onPress={this.navigateToAboutMe}
>
<Text style={ProfileEditStyle.text}>Edit About Me</Text>
</TouchableOpacity>
<TouchableOpacity
style={ProfileEditStyle.buttons}
onPress={this.navigateToInterests}
>
<Text style={ProfileEditStyle.text}>Edit Interests</Text>
</TouchableOpacity>
</View>
</View>
);
}
}
export default EditProfile;
This is screen 2, where I want the state for the buttonText to change on the continue button component.
export class AboutUser extends Component {
constructor(props) {
super(props);
this.navigatToInterests = this.navigatToInterests.bind(this);
this.checkEntry = this.checkEntry.bind(this);
var params = props.navigation.state.params.aboutUser;
this.state = {
value: "",
};
}
<ContinueButton
text={this.props.route.params.aboutUser.buttonText}
color="#ff304f"
style={CreateAboutMe.centerButton}
onPress={this.navigatToInterests}
/>
I am trying to do conditional rendering for the continue button component. When its on one screen I want it to say "continue" and when its on another route I want it to say " Save and Go Back". However when I try to change the state between screens for some reason I either get a params error or the state doesn't change.
Get parameter from previous screen :
constructor(){
const isShowBtn = this.props.navigation.getParam("showing");
this.state = {
value: isShowBtn
}
}

How to navigate other component when use bind()?

I use react-navigation to navigate other component.
Now i want to navigate to other component with some params(selectedCity态firstSliderValue态secondSliderValue), but onAccept() function will get the error
TypeError: Cannot read property 'bind' of undefined
When i added the params before, i can navigate to my MovieClostTime component. Why i can not add params ? What should i do ?
Any help would be appreciated. Thanks in advance.
Here is my part of code:
constructor(props) {
super(props);
this.state = {
showModal: false,
selectedCity: 'Keelung',
firstSliderValue: 18,
secondSliderValue: 21
};
}
// it will close <Confirm /> and navigate to MovieCloseTime component
onAccept() {
this.setState({ showModal: !this.state.showModal });
const { selectedCity, firstSliderValue, secondSliderValue } = this.state;
console.log(selectedCity); // Keelung
console.log(firstSliderValue); // 18
console.log(secondSliderValue); // 21
this.props.navigation.navigate('MovieCloseTime', {
selectedCity,
firstSliderValue,
secondSliderValue
});
}
// close the Confirm
onDecline() {
this.setState({ showModal: false });
}
render() {
if (!this.state.isReady) {
return <Expo.AppLoading />;
}
const movies = this.state.movies;
console.log('render FirestScrren');
return (
<View style={{ flex: 1 }}>
{/* Other View */}
{/* <Confirm /> is react-native <Modal />*/}
<Confirm
visible={this.state.showModal}
onAccept={this.onAccept.bind(this)}
onDecline={this.onDecline.bind(this)}
onChangeValues={this.onChangeValues}
>
</Confirm>
</View>
);
}
My Confirm.js
import React from 'react';
import { Text, View, Modal } from 'react-native';
import { DropDownMenu } from '#shoutem/ui';
import TestConfirm from './TestConfirm';
import { CardSection } from './CardSection';
import { Button } from './Button';
import { ConfirmButton } from './ConfirmButton';
const Confirm = ({ children, visible, onAccept, onDecline, onChangeValues }) => {
const { containerStyle, textStyle, cardSectionStyle } = styles;
return (
<Modal
visible={visible}
transparent
animationType="slide"
onRequestClose={() => {}}
>
<View style={containerStyle}>
<CardSection style={cardSectionStyle}>
<TestConfirm onChangeValues={onChangeValues} />
{/* <Text style={textStyle}>
{children}
</Text> */}
</CardSection>
<CardSection>
<ConfirmButton onPress={onAccept}>Yes</ConfirmButton>
<ConfirmButton onPress={onDecline}>No</ConfirmButton>
</CardSection>
</View>
</Modal>
);
};
const styles = {
// some style
};
export { Confirm };

Flux (alt), TabBarIOS, and Listeners and tabs that have not yet been touched / loaded

I've got a problem that I'm sure has a simple solution, but I'm new to React and React Native so I'm not sure what I'm missing.
My app has a TabBarIOS component at its root, with two tabs: TabA and TabB. TabB is subscribed to events from a Flux store (I'm using alt) that TabA creates. TabA basically enqueues items that TabB plays. This part of the code is fine and works as expected.
The problem is that TabA is the default tab so the user can use TabA an enqueue items, but because TabB hasn't been touched/clicked the TabB component hasn't been created so it's listener hasn't been registered. Only when TabB is pressed does it get created and correctly receive events.
So how can I ensure the TabB component gets created when the TabBarIOS component is rendered? Do I need to something hacky like set the active tab to TabB on initial load and flip it back to TabA before the user does anything?
Yes, you'll need to do something hacky if you're not using a Navigator component. If you're using Navigatoryou can specify a set of routes to initially mount with the initialRouteStackprop. This is however going to need you to modify a bit the way your app works I think.
If not using Navigator, you'll indeed have to do something hacky as you suggested. I've set up a working example here based on RN's TabBar example.
Below you'll find the code of this example, check the console.log (they don't seem to work on rnplay) to see that that components are mounted on opening the app.
Example Code
var React = require('react-native');
var {
AppRegistry,
Component,
Image,
StyleSheet,
TabBarIOS,
Text,
View
} = React;
import _ from 'lodash';
var base64Icon = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEsAAABLCAQAAACSR7JhAAADtUlEQVR4Ac3YA2Bj6QLH0XPT1Fzbtm29tW3btm3bfLZtv7e2ObZnms7d8Uw098tuetPzrxv8wiISrtVudrG2JXQZ4VOv+qUfmqCGGl1mqLhoA52oZlb0mrjsnhKpgeUNEs91Z0pd1kvihA3ULGVHiQO2narKSHKkEMulm9VgUyE60s1aWoMQUbpZOWE+kaqs4eLEjdIlZTcFZB0ndc1+lhB1lZrIuk5P2aib1NBpZaL+JaOGIt0ls47SKzLC7CqrlGF6RZ09HGoNy1lYl2aRSWL5GuzqWU1KafRdoRp0iOQEiDzgZPnG6DbldcomadViflnl/cL93tOoVbsOLVM2jylvdWjXolWX1hmfZbGR/wjypDjFLSZIRov09BgYmtUqPQPlQrPapecLgTIy0jMgPKtTeob2zWtrGH3xvjUkPCtNg/tm1rjwrMa+mdUkPd3hWbH0jArPGiU9ufCsNNWFZ40wpwn+62/66R2RUtoso1OB34tnLOcy7YB1fUdc9e0q3yru8PGM773vXsuZ5YIZX+5xmHwHGVvlrGPN6ZSiP1smOsMMde40wKv2VmwPPVXNut4sVpUreZiLBHi0qln/VQeI/LTMYXpsJtFiclUN+5HVZazim+Ky+7sAvxWnvjXrJFneVtLWLyPJu9K3cXLWeOlbMTlrIelbMDlrLenrjEQOtIF+fuI9xRp9ZBFp6+b6WT8RrxEpdK64BuvHgDk+vUy+b5hYk6zfyfs051gRoNO1usU12WWRWL73/MMEy9pMi9qIrR4ZpV16Rrvduxazmy1FSvuFXRkqTnE7m2kdb5U8xGjLw/spRr1uTov4uOgQE+0N/DvFrG/Jt7i/FzwxbA9kDanhf2w+t4V97G8lrT7wc08aA2QNUkuTfW/KimT01wdlfK4yEw030VfT0RtZbzjeMprNq8m8tnSTASrTLti64oBNdpmMQm0eEwvfPwRbUBywG5TzjPCsdwk3IeAXjQblLCoXnDVeoAz6SfJNk5TTzytCNZk/POtTSV40NwOFWzw86wNJRpubpXsn60NJFlHeqlYRbslqZm2jnEZ3qcSKgm0kTli3zZVS7y/iivZTweYXJ26Y+RTbV1zh3hYkgyFGSTKPfRVbRqWWVReaxYeSLarYv1Qqsmh1s95S7G+eEWK0f3jYKTbV6bOwepjfhtafsvUsqrQvrGC8YhmnO9cSCk3yuY984F1vesdHYhWJ5FvASlacshUsajFt2mUM9pqzvKGcyNJW0arTKN1GGGzQlH0tXwLDgQTurS8eIQAAAABJRU5ErkJggg==';
class StackOverflowApp extends Component {
constructor(props) {
super(props);
this.state = {
selectedTab: 'blueTab',
notifCount: 0,
presses: 0
};
}
_renderContent = (color, pageText, num) => {
return (
<View style={[styles.tabContent, {backgroundColor: color}]}>
<Text style={styles.tabText}>{pageText}</Text>
<Text style={styles.tabText}>{num} re-renders of the {pageText}</Text>
</View>
);
};
componentWillMount() {
this.setState({selectedTab: 'redTab'});
}
componentDidMount() {
this.setState({selectedTab: 'blueTab'});
}
render () {
return (
<View style={{flex: 1}}>
<TabBarIOS
tintColor="white"
barTintColor="darkslateblue">
<TabBarIOS.Item
title="Blue Tab"
icon={{uri: base64Icon, scale: 3}}
selected={this.state.selectedTab === 'blueTab'}
onPress={() => {
this.setState({
selectedTab: 'blueTab',
});
}}>
<Page1 />
</TabBarIOS.Item>
<TabBarIOS.Item
systemIcon="history"
badge={this.state.notifCount > 0 ? this.state.notifCount : undefined}
selected={this.state.selectedTab === 'redTab'}
onPress={() => {
this.setState({
selectedTab: 'redTab'
});
}}>
<Page2 />
</TabBarIOS.Item>
</TabBarIOS>
</View>
);
};
}
class Page1 extends Component {
static route() {
return {
component: Page1
}
};
constructor(props) {
super(props);
}
componentWillMount() {
console.log('page 1 mount');
}
componentWillUnmount() {
console.log('page 1 unmount');
}
render() {
return (
<View style={styles.tabContent}>
<Text style={styles.tabText}>Page 1</Text>
</View>
);
}
}
class Page2 extends Component {
static route() {
return {
component: Page2
}
};
constructor(props) {
super(props);
}
componentWillMount() {
console.log('page 2 mount');
}
componentWillUnmount() {
console.log('page 2 unmount');
}
render() {
return (
<View style={styles.tabContent}>
<Text style={styles.tabText}>Page 2</Text>
</View>
);
}
}
const styles = StyleSheet.create({
tabContent: {
flex: 1,
backgroundColor: 'green',
alignItems: 'center',
},
tabText: {
color: 'white',
margin: 50,
},
});
AppRegistry.registerComponent('StackOverflowApp', () => StackOverflowApp);