Render Component Fixed Number of Times (Asynchronously) - javascript

I want to render the same component a fixed number of times(entered by the user) one after the other (Asynchronously). For this, I have used the below function passing as props approach where a while loop is used to make the code run asynchronously and could progress only after the state variable componentRendered becomes true, but it's not working. Could someone help to figure this out. Thanks in advance.
HomeScreen.js
import {View, Text} from 'react-native';
import Stepper from '../components/Stepper';
class HomeScreen extends Component {
constructor(props) {
super(props);
this.state = {
componentRendered: false,
};
}
setComponentRender = () => {
this.setState({componentRendered: true});
};
render() {
var stepperElement = [];
for (let i = 1; i <= 2; i++) {
stepperElement.push(
<Stepper setComponentRender={this.setComponentRender} />,
);
while (this.state.componentRendered === false) {}
this.setState({componentRendered: false});
}
return <View>{stepperElement}</View>;
}
}
export default HomeScreen;
Stepper.js
import {View, TextInput, Text, Alert} from 'react-native';
import {ProgressSteps, ProgressStep} from 'react-native-progress-steps';
class Stepper extends Component {
constructor(props) {
super(props);
this.state = {
name: '',
};
}
static navigationOptions = {
header: null,
};
defaultScrollViewProps = {
keyboardShouldPersistTaps: 'handled',
contentContainerStyle: {
flex: 1,
justifyContent: 'center',
},
};
onNextStep = () => {
console.log('called next step');
};
onPaymentStepComplete = () => {
Alert.alert(
'Payment completed!',
'Your Payment is Successful',
[
{
text: 'Cancel',
onPress: () => console.log('Cancel Pressed'),
style: 'cancel',
},
{text: 'OK', onPress: () => console.log('OK Pressed')},
],
{cancelable: false},
);
};
onPrevStep = () => {
console.log('called previous step');
};
onSubmitSteps = () => {
console.log('called on submit step.');
this.props.setComponentRender();
};
render() {
return (
<View style={{flex: 1, marginTop: 50}}>
<ProgressSteps>
<ProgressStep
label="Payment"
onNext={this.onPaymentStepComplete}
onPrevious={this.onPrevStep}
scrollViewProps={this.defaultScrollViewProps}>
<View style={{alignItems: 'center'}}>
<Text>Payment step content</Text>
</View>
</ProgressStep>
<ProgressStep
label="Confirm Order"
onPrevious={this.onPrevStep}
onSubmit={this.onSubmitSteps}
scrollViewProps={this.defaultScrollViewProps}>
<View style={{alignItems: 'center'}}>
<Text>Confirm order step content</Text>
</View>
</ProgressStep>
</ProgressSteps>
</View>
);
}
}
export default Stepper;

Related

React Native (Expo): TouchableOpacity onPress is not a function / is undefined

I was following this tutorial on Linkedin-Learning and suddelny my code wouldn't work anymore.
Unfortunately i don't really understand these error messages:
This warning always appears:
Warning: Failed prop type: The prop onPress is marked as required in
RandomNumber, but its value is undefined.
And if I press one of the "buttons", this error messages comes up:
TypeError: _this.props.onPress is not a function. (In
'_this.props.onPress(_this.props.id)', '_this.props.onPress' is
undefined)
RandomNumber.js:
import React from "react";
import { Text, TouchableOpacity, StyleSheet } from "react-native";
import PropTypes from "prop-types";
class RandomNumber extends React.Component {
static propTypes = {
id: PropTypes.number.isRequired,
number: PropTypes.number.isRequired,
isDisabled: PropTypes.bool.isRequired,
onPress: PropTypes.func.isRequired,
};
handlePress = () => {
if (this.props.isDisabled) {
return;
}
this.props.onPress(this.props.id);
};
render() {
return (
<TouchableOpacity onPress={this.handlePress}>
<Text style={[styles.random, this.props.isDisabled && styles.disabled]}>
{this.props.number}
</Text>
</TouchableOpacity>
);
}
}
const styles = StyleSheet.create({
random: {
backgroundColor: "#999",
width: 120,
marginHorizontal: 15,
marginVertical: 25,
fontSize: 35,
textAlign: "center",
},
disabled: {
opacity: 0.2,
},
});
export default RandomNumber;
Game.js:
import React from "react";
import { View, Text, Button, StyleSheet } from "react-native";
import PropTypes from "prop-types";
import RandomNumber from "./RandomNumber";
import shuffle from "lodash.shuffle";
class Game extends React.Component {
static propTypes = {
randomNumberCount: PropTypes.number.isRequired,
initialSeconds: PropTypes.number.isRequired,
onPlayAgain: PropTypes.func.isRequired,
};
state = { selectedIds: [], remainingSeconds: this.props.initialSeconds };
gameStatus = "PLAYING";
randomNumbers = Array.from({ length: this.props.randomNumberCount }).map(
() => 1 + Math.floor(10 * Math.random())
);
target = this.randomNumbers
.slice(0, this.props.randomNumberCount - 2)
.reduce((acc, curr) => acc + curr, 0);
shuffledRandomNumbers = shuffle(this.randomNumbers);
componentDidMount() {
this.intervalID = setInterval(() => {
this.setState(
(prevState) => {
return { remainingSeconds: prevState.remainingSeconds - 1 };
},
() => {
if (this.state.remainingSeconds === 0) {
clearInterval(this.intervalID);
}
}
);
}, 1000);
}
componentWillUnmount() {
clearInterval(this.intervalID);
}
isNumberSelected = (numberIndex) => {
return this.state.selectedIds.indexOf(numberIndex) >= 0;
};
selectNumber = (numberIndex) => {
this.setState((prevState) => ({
selectedIds: [...prevState.selectedIds, numberIndex],
}));
};
UNSAFE_componentWillUpdate(nextProps, nextState) {
if (
nextState.selectedIds !== this.state.selectedIds ||
nextState.remainingSeconds === 0
) {
this.gameStatus = this.calcGameStatus(nextState);
if (this.gameStatus !== "PLAYING") {
clearInterval(this.intervalID);
}
}
}
calcGameStatus = (nextState) => {
const sumSelected = nextState.selectedIds.reduce((acc, curr) => {
return acc + this.shuffledRandomNumbers[curr];
}, 0);
if (this.state.remainingSeconds === 0) {
return "LOST";
}
if (sumSelected < this.target) {
return "PLAYING";
}
if (sumSelected === this.target) {
return "WON";
}
if (sumSelected > this.target) {
return "LOST";
}
};
render() {
const gameStatus = this.gameStatus;
return (
<View style={styles.container}>
<Text style={[styles.target, styles[`STATUS_${gameStatus}`]]}>
{this.target}
</Text>
<View style={styles.randomContainer}>
{this.shuffledRandomNumbers.map((randomNumber, index) => (
<RandomNumber
key={index}
id={index}
number={randomNumber}
onPress={this.state.selectNumber}
isDisabled={
this.isNumberSelected(index) || gameStatus !== "PLAYING"
}
/>
))}
</View>
{this.gameStatus !== "PLAYING" && (
<Button title="Play Again" onPress={this.props.onPlayAgain} />
)}
<Text>{this.state.remainingSeconds}</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
backgroundColor: "#ddd",
flex: 1,
},
target: {
fontSize: 40,
backgroundColor: "#bbb",
margin: 50,
textAlign: "center",
},
randomContainer: {
flex: 1,
flexDirection: "row",
flexWrap: "wrap",
justifyContent: "space-around",
},
STATUS_PLAYING: {
backgroundColor: "#bbb",
},
STATUS_WON: {
backgroundColor: "green",
},
STATUS_LOST: {
backgroundColor: "red",
},
});
export default Game;
App.js:
import React from "react";
import Game from "./Game";
class App extends React.Component {
state = { gameId: 1 };
resetGame = () => {
this.setState((prevState) => {
return { gameId: prevState.gameId + 1 };
});
};
render() {
return (
<Game
key={this.state.gameId}
onPlayAgain={this.resetGame}
randomNumberCount={6}
initialSeconds={10}
/>
);
}
}
export default App;
I've already tried some solutions from other posts, but none of them worked.
Any help is appreciated.

React Native Issue

I am building a react native app that uses the Wordpress api. I am having problems displaying the cart and receive this error.
Object {} error [Error: Request failed with status code 404]
undefined
I have tried everything and have figures it might be a problem with Axios...
Please advise me on what I can do...
CartAction.js
import * as types from '../constants/ActionTypes';
import CartApi from '../api/CartApi';
export function getCart() {
return (dispatch) => {
return CartApi.getCart().then(cart => {
dispatch(getCartSuccess(cart));
}).catch(err => {
//TODO:get correct error msg
console.log(err.error);
})
};
}
function getCartSuccess(cart) {
return {
type: types.GET_CART_SUCCESS,
cart
};
}
export function addToCart(product, quantity) {
return (dispatch) => {
return CartApi.addToCart(product, quantity).then(cartUpdate => {
dispatch(addToCartSuccess(cartUpdate));
}).catch(err => {
//TODO:get correct error msg
console.log('error',err);
})
};
}
function addToCartSuccess(cartUpdate) {
return {
type: types.ADD_TO_CART_SUCCESS,
cartUpdate
};
}
CartPage.js
import React from 'react'
import { StyleSheet, Text, View, FlatList, Image } from 'react-native'
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import * as CartAction from '../../actions/CartAction';
class CartPage extends React.Component {
constructor(props) {
super(props);
this.state = {
cart: {}
}
}
componentDidMount() {
this.props.CartAction.getCart();
}
_keyExtractor = (item, index) => item.key;
render() {
console.log(this.props.cart)
const cartObject = this.props.cart;
var cartArray = [];
Object.keys(cartObject).forEach(function(key) {
cartArray.push(cartObject[key]);
});
const Items = <FlatList contentContainerStyle={styles.list}
data={cartArray}
keyExtractor={this._keyExtractor}
renderItem={({ item }) =>
// <TouchableHighlight style={{width:'50%'}} onPress={() => navigate("Product", { product: item })} underlayColor="white">
<View style={styles.lineItem} >
<Image style={styles.image} source={{uri: item.product_image}} />
<Text style={styles.text}>{item.product_name}</Text>
<Text style={styles.text}>{item.quantity}</Text>
</View>
// </TouchableHighlight>
}
/>;
return (
<View style={styles.container}>
{Items}
</View>
)
}
}
const styles = StyleSheet.create({
lineItem: {
flexDirection: 'row'
},
list: {
flexDirection: 'column'
},
image: {
width: 50,
height: 50
},
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
text: {
fontSize: 20,
padding: 5
}
})
function mapStateToProps(state) {
return {
cart: state.cart
};
}
function mapDispatchToProps(dispatch) {
return {
CartAction: bindActionCreators(CartAction, dispatch)
};
}
export default connect(mapStateToProps, mapDispatchToProps)(CartPage);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

React-navigation how to pass data down to navigator objects

Consider the following example:
import { AppRegistry } from "react-native";
import React, { Component } from "react";
import {
createSwitchNavigator,
createStackNavigator,
createBottomTabNavigator
} from "react-navigation";
import Icon from "react-native-vector-icons/Ionicons";
import { withNavigation } from "react-navigation";
import {
View,
Text,
Platform,
TouchableNativeFeedback,
TouchableOpacity,
StyleSheet
} from "react-native";
const Touchable =
Platform.OS === "android" ? TouchableNativeFeedback : TouchableOpacity;
class ListComponent extends Component {
static navigationOptions = {
title: "List"
};
handleGo = () => {
this.props.navigation.navigate("Board");
};
render = () => {
//??? How to get myData ???
return (
<View>
<Text>HELLO LIST!!!!</Text>
<Touchable onPress={this.handleGo}>
<Text>GO TO BOARD</Text>
</Touchable>
<Text>{myData}</Text>
</View>
);
};
}
const List = withNavigation(ListComponent);
class BoardComponent extends Component {
static navigationOptions = {
title: "Board"
};
//??? How to get myData ???
render = () => {
return (
<View>
<Text>HELLO BOARD!!!!</Text>
<Text>{myData}</Text>
</View>
);
};
}
const Board = BoardComponent;
class PanelComponent extends Component {
static navigationOptions = {
title: "Panel"
};
//??? How to get myData ???
render = () => {
return (
<View>
<Text>HELLO PANEL!!!!</Text>
<Text>{myData}</Text>
</View>
);
};
}
const Panel = PanelComponent;
const Test0 = createStackNavigator(
{
List: {
screen: List
},
Board: {
screen: Board
}
},
{
navigationOptions: {
headerStyle: {
backgroundColor: "grey"
},
headerTintColor: "blue",
headerTitleStyle: {
fontWeight: "bold"
}
}
}
);
const Test1 = createStackNavigator(
{
Panel: {
screen: Panel
}
},
{
navigationOptions: {
headerStyle: {
backgroundColor: "grey"
},
headerTintColor: "blue",
headerTitleStyle: {
fontWeight: "bold"
}
}
}
);
const LoggedInNavigator = createBottomTabNavigator(
{
Test0: {
screen: Test0,
navigationOptions: {
tabBarIcon: ({ tintColor, focused }) => (
<Icon
name={"ios-list-box-outline"}
size={24}
color={"#cdcdcd"}
/>
)
}
},
Test1: {
screen: Test1,
navigationOptions: {
tabBarIcon: ({ tintColor, focused }) => (
<Icon
name={"ios-construct-outline"}
size={24}
color={"#cdcdcd"}
/>
)
}
}
},
{
tabBarOptions: {
showLabel: false,
activeTintColor: "white",
activeBackgroundColor: "blue",
style: {
backgroundColor: "grey"
}
},
animationEnabled: true,
swipeEnabled: true,
initialRouteName: "Test1"
}
);
export const createRootNavigator = () => {
let myData = getMyDataFromDB(); // <=== How can I pass myData down to Panel/Board/List
return createSwitchNavigator(
{
LoggedIn: {
screen: LoggedInNavigator
}
},
{
initialRouteName: "LoggedIn"
}
);
};
class App extends Component {
render = () => {
const Layout = createRootNavigator();
return <Layout />;
};
}
export default App;
AppRegistry.registerComponent("app", () => App);
How can I pass down myData through all the routes to the end components?
This is a skeleton of a much bigger application where I query for data on the root navigator (createRootNavigator) that must be served to some components down the navigation tree.
You could make a Higher Order Component or a wrapper component that handles the fetching of your data in componentDidMount and wrap all your routes with it
// HOC component example
import React from 'react';
const withMyData = (WrappedComponent) => {
class myEnchancedComponent extends React.Component {
state ={ myData: null }
componentDidMount() {
let myData = getMyDataFromDB();
// set the state after you get the data
this.setState({myData})
}
render() {
const {myData} = this.state;
return (
<WrappedComponent {...this.props} myData={myData}
/>
);
}
}
return myEnchancedComponent;
};
export default withMyData;
// example of how to use it
const List = withMyData(withNavigation(ListComponent));
The are other ways you can solve this too. You could use redux combined with redux-persist to store your data and make them available even offline.
He you can use redux for that, or another way is using local storage (react-native-local-storage), with this lib you can storage any data and in any moment or page you can access it.

Issue with photos length

I am facing 2 issues related to length of my selected photos:
When selecting photos, it lets me to select 5 photos without any issue (it fits my length restriction), however it doesn't save the chosen photos, when I go to the next screen. In another scenario, when I am at the same screen where I choose photos and I choose 6 photos, it selects the 6 photo but the warning popup will appear and say that its currently supports 5, then when I go to next screen its saves the selected photos unlike previously.
If I deselect photos and then try to select another photos (still in my length limit) popup jumps with selection limit and doesn't let me choose photos, when I go to the next screen it saves the changes from previous selection and not from current one.
import React from 'react';
import {
View,
ScrollView,
Image,
Dimensions,
TextInput,
Text,
StatusBar,
TouchableHighlight,
Linking,
Keyboard,
CameraRoll,
KeyboardAvoidingView
} from 'react-native';
import {connect} from 'react-redux';
import {ActionCreators} from '../redux/actions';
import {bindActionCreators} from 'redux';
import Colors from '../constants/Colors';
import api from '../api';
import {
getEmailAddress,
showError,
renderMessageBar,
registerMessageBar,
unregisterMessageBar
} from '../utils/ComponentUtils';
import {
regularHeader,
mainHeader
} from '../utils/Headers';
import {NavigationActions} from 'react-navigation';
import {SelectionLimitDialog} from '../utils/Dialogs';
import {ifIphoneX, isIphoneX} from 'react-native-iphone-x-helper';
import {SafeAreaView} from 'react-navigation';
// specific component imports.
import {List, ListItem} from 'react-native-elements'
import {Button} from 'react-native-elements'
import Loader from '../components/Loader';
import LoaderError from '../components/LoaderError';
import SelectedPhoto from '../components/SelectedPhoto';
class MultiSafeeScreen extends React.Component
{
static navigationOptions = ({navigation}) => {
const {params} = navigation.state;
const isIncome = params ? params.isIncome : false;
const notificationAction = params ? params.notificationAction : () => {};
const isShowBack = params ? params.isShowBack : false;
return mainHeader({
isShowBack: isShowBack,
backAction: () => navigation.goBack(),
notificationAction: () => notificationAction(),
income: isIncome
});
};
constructor(props) {
super(props);
this.selectedPhotos = [];
this.state = {
photos: null,
loader: {
loading: 0,
message: "Loading photos..."
},
selectedPhotos: [],
supportLength: 5
};
this.props.navigation.setParams({notificationAction: this.onNotification, isIncome: this.props.isNewNotifications});
}
UNSAFE_componentWillReceiveProps(newProps) {
if (newProps.isNewNotifications !== this.props.isNewNotifications) {
this.props.navigation.setParams({notificationAction: this.onNotification, isIncome: newProps.isNewNotifications});
}
}
componentDidMount() {
registerMessageBar(this.refs.alert);
let options = {
first: 30,
assetType: 'Photos',
}
CameraRoll.getPhotos(options)
.then(r => {
this.setState({
photos: r.edges,
loader: {
loading: 1,
message: "Loading photos..."
},
});
})
.catch((err) => {
//Error Loading Images
});
StatusBar.setHidden(false);
}
componentWillUnmount() {
unregisterMessageBar();
this.props.setSelectedPhotos(0);
}
onNotification = () => {
this.props.setNewNotifications(false);
this.props.navigation.navigate("Notifications");
}
closeKeyboard = () => {
Keyboard.dismiss();
}
onSelectPhoto = (photo, index) => {
let photos = new Set([...this.selectedPhotos]);
let len = photos.size + 1 ;
console.log('photos')
if (len > this.state.supportLength) {
this.limitDialog.open();
this.setState({selectedPhotos: this.selectedPhotos});
this.props.setSelectedPhotos(len);
}
else {
photos.add(photo);
this.selectedPhotos = Array.from(photos);
}
}
onDeselectPhoto = (photo, index) => {
let photos = new Set([...this.state.selectedPhotos]);
let len = photos.size - 1;
photos.delete(photo);
this.setState({selectedPhotos: Array.from(photos)});
this.props.setSelectedPhotos(len);
}
onNext = () => {
this.props.navigation.navigate("MultiSafeeCreate", {
isShowBack: true,
selected: [...this.state.selectedPhotos]
});
}
renderLoader() {
let {width, height} = Dimensions.get('window');
let photoWidth = width/3;
if (this.state.loader.loading === 0) {
return <Loader style={{justifyContent: 'center', alignItems: 'center'}} message={this.state.loader.message}/>
}
else if (this.state.loader.loading === 2) {
return <LoaderError style={{justifyContent: 'center', alignItems: 'center'}} message={this.state.loader.message}/>
}
// if photos are null do nothing, else if empty show onbording
// if has photos show photos.
if (this.state.photos === null) {
return <Loader style={{justifyContent: 'center', alignItems: 'center'}} message={this.state.loader.message}/>
}
else {
return (
<View style={{width: width, maxHeight: 600}}>
<ScrollView >
<View style={{flexDirection: 'row', width: width, flexWrap: 'wrap',marginBottom:40, justifyContent: 'space-between'}}>
{
this.state.photos.map((p, i) => {
return (
<SelectedPhoto
key={i}
index={i}
style={{
width: photoWidth,
height: photoWidth,
}}
borderColor = "white"
limit={this.state.supportLength}
photo={p}
onSelectPhoto={this.onSelectPhoto}
onDeselectPhoto={this.onDeselectPhoto}
/>
);
})
}
</View>
</ScrollView>
<View style={{ position:'absolute', right:-15, top:475 }}>
<Button
onPress={this.onNext}
containerViewStyle={{width: width}}
backgroundColor={Colors.red}
title='NEXT' />
</View>
</View>
);
}
}
render() {
return (
<View style={{flex: 1, backgroundColor: Colors.white}}>
{this.renderLoader()}
<SelectionLimitDialog ref={(el) => this.limitDialog = el} />
{renderMessageBar()}
</View>
);
}
}
function mapDispatchToProps(dispatch) {
return bindActionCreators(ActionCreators, dispatch);
}
function mapStatesToProps(state) {
return {
isNewNotifications: state.isNewNotifications
};
}
export default connect(mapStatesToProps, mapDispatchToProps)(MultiSafeeScreen);

navigate to another screen from tab-view screen not working

following is my code:- posting full code
index.android.js
import React, { Component } from 'react';
import { AppRegistry, Text, StyleSheet, View, NetInfo, Alert, AsyncStorage } from 'react-native';
import Splash from './app/screens/Splash'
import { StackNavigator } from 'react-navigation'
import Login from './app/screens/Login'
import Register from './app/screens/Register'
import Check from './app/screens/Check'
import Qwerty from './app/screens/Qwerty'
import Home from './app/screens/Home'
var STORAGE_KEY = 'token';
var DEMO_TOKEN;
class Splashscreen extends React.Component {
static navigationOptions = {
header: null
};
async componentDidMount() {
const { navigate } = this.props.navigation;
var DEMO_TOKEN = await AsyncStorage.getItem(STORAGE_KEY);
if (DEMO_TOKEN === undefined) {
navigate("Login");
} else if (DEMO_TOKEN === null) {
navigate("Splash");
} else {
navigate("Temp");
}
};
render() {
const { navigate } = this.props.navigation;
return(
<View style={styles.wrapper}>
<View style={styles.titlewrapper}>
<Text style={styles.title}> Loding... </Text>
</View>
</View>
);
}
}
const Section = StackNavigator({
Root: {screen: Splashscreen},
Splash: { screen: Splash },
Login: { screen: Login },
Registerscreen: { screen: Register },
Temp: { screen: Check },
Qwerty:{screen: Qwerty},
Home:{screen: Home},
});
AppRegistry.registerComponent('shopcon', () => Section);
here i can navigate properly without any error Now,
This is my tab.js => Here i given three tabs (mainly working in first home.js)
import React, { PureComponent } from 'react';
import { Animated, StyleSheet,View } from 'react-native';
import { TabViewAnimated, TabBar } from 'react-native-tab-view';
import { StackNavigator } from 'react-navigation';
import Qwerty from './Qwerty';
import Home from './Home';
//import Login from './Login'
import type { NavigationState } from 'react-native-tab-view/types';
type Route = {
key: string,
title: string,
};
type State = NavigationState<Route>;
class Tab extends PureComponent<void, *, State> {
static navigationOptions = {
header: null
};
state: State = {
index: 0,
routes: [
{ key: '1', title: 'Home' },
{ key: '2', title: 'Shops' },
{ key: '3', title: 'Bookmark' },
],
};
_first: Object;
_second: Object;
_third: Object;
_handleIndexChange = index => {
this.setState({
index,
});
};
_renderLabel = props => ({ route, index }) => {
const inputRange = props.navigationState.routes.map((x, i) => i);
const outputRange = inputRange.map(
inputIndex => (inputIndex === index ? '#fff' : '#222')
);
const color = props.position.interpolate({
inputRange,
outputRange,
});
return (
<View>
<Animated.Text style={[styles.label, { color }]}>
{route.title}
</Animated.Text>
</View>
);
};
_renderHeader = props => {
return (
<TabBar
{...props}
pressColor="#999"
// onTabPress={this._handleTabItemPress}
renderLabel={this._renderLabel(props)}
indicatorStyle={styles.indicator}
tabStyle={styles.tab}
style={styles.tabbar}
/>
);
};
_renderScene = ({ route }) => {
switch (route.key) {
case '1':
return (
<Home
ref={el => (this._first = el)}
style={[styles.page, { backgroundColor: '#E3F4DD' }]}
/>
);
case '2':
return (
<Qwerty
ref={el => (this._second = el)}
style={[styles.page, { backgroundColor: '#E6BDC5' }]}
initialListSize={1}
/>
);
case '3':
return (
<Qwerty
ref={el => (this._third = el)}
style={[styles.page, { backgroundColor: '#EDD8B5' }]}
initialListSize={1}
/>
);
default:
return null;
}
};
render() {
return (
<TabViewAnimated
style={[styles.container, this.props.style]}
navigationState={this.state}
renderScene={this._renderScene}
renderHeader={this._renderHeader}
onIndexChange={this._handleIndexChange}
// onRequestChangeTab={this._handleIndexChange}
lazy
/>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
indicator: {
backgroundColor: '#fff',
},
label: {
fontSize: 18,
fontWeight: 'bold',
margin: 8,
},
tabbar: {
backgroundColor: '#ff6600',
},
tab: {
opacity: 1,
// width: 140,
},
page: {
backgroundColor: '#f9f9f9',
},
});
export default Tab;
This is Home.js => It is running well if i am using it directly but not running when using it in Tab.js
GoPressed(navigate){
navigate("Registerscreen");
}
render() {
const { navigate } = this.props.navigation;
contents = this.state.qwerty.data.map((item) => {
return (
<View>
{item.p1.shareproductid ? <TouchableHighlight onPress={() => this.GoPressed(navigate)} style={styles.button}>
<Text style={styles.buttonText}>
Go
</Text>
</TouchableHighlight> : null }
<Text>
{item.p1.content}
</Text>
</View>
);
});
return (
<ScrollView style={styles.container}>
{contents}
</ScrollView>
);
}
I am trying to navigate on Register screen after Go button pressed, But here it shows me error. I have used same navigation method before they works correctly but here it gives error. please show where i am going wrong?
How to navigate to any other(not these three screens of tab-view ) screen from tab-view?
I tried running Home.js in other way means not using in tab view then it is running and navigation also works but when i am calling Home.js in tab-view i.e in Tab.js then it showing error as in screenshot.
Seems like you're navigating to the wrong screen name.
This should do it.
GoPressed(navigate){
navigate("Registerscreen");
}
I honestly can't test out your code as it'll take too much time.
How about you check out this simple working example of what your looking for and match it with your code.
Go the Settings tab and then you can click on the button to navigate to the other Registerscreen which is not in the Tabs.
https://snack.expo.io/HJ5OqS5qZ

Categories