How to get variable react native - android

I'm using react native expo for the following project basically i want to retrive the selected item form an flat list and display it in a modal
import React,{ Component}from 'react';
import {View,Text,Image,StyleSheet,Modal,Button} from 'react-native';
import { FlatList, TouchableOpacity, ScrollView } from 'react-native-gesture-handler';
import Card from '../shared/card';
import { AppLoading } from 'expo';
import * as Font from 'expo-font';
export default class MealSearch extends Component{
constructor(props){
super(props)
this.state = {
loaded:false,
show:false,
key:''
}}
render(){
const meal= [ {title:'My hero Academia',img:{uri:'https://i.cdn.turner.com/adultswim/big/img/2018/05/10/MHA_Header.png'}, body:'Rating : 4.5/5' , id :'1'},
{title:'Naruto',img:{uri:'https://store-images.s-microsoft.com/image/apps.15041.71343510227343465.377174a9-abc8-4da3-aaa6-8874fdb9e2f5.00fc0a9e-295e-40ca-a391-58ed9f83e9a0?mode=scale&q=90&h=1080&w=1920&background=%23FFFFFF'}, body:'Rating : 5/5' , id :'2'},
{title:'Attack On Titan',img:{uri:'https://www.denofgeek.com/wp-content/uploads/2013/12/attack-on-titan-main.jpg?fit=640%2C380'}, body:'Rating : 4.5/5' , id :'3'},
{title:'Fate: Unlimited Blade Works',img:{uri:'https://derf9v1xhwwx1.cloudfront.net/image/upload/c_fill,q_60,h_750,w_1920/oth/FunimationStoreFront/2066564/Japanese/2066564_Japanese_ShowDetailHeaderDesktop_496a6d81-27db-e911-82a8-dd291e252010.jpg'}, body:'Rating : 4.5/5' , id :'4'}
]
const handlePress = (meal_data) =>{
this.setState({show: true});
this.setState({selectedMeal:meal_data});
console.log(meal_data)
}
return(
<View style={styles.view} >
<FlatList
keyExtractor={item => item.id}
data={meal}
renderItem={({item})=>(
<Card>
<TouchableOpacity onPress={(_item)=>{handlePress(item)}}>
<View style={styles.mealItem}>
<Image style={{width:300,height:150}} resizeMode={'contain'} source={item.img} marginLeft={30}/>
<View style={styles.descrip}>
<Text style={styles.rating}>{item.title}</Text>
<Text style={styles.name}>{item.body}</Text>
</View>
</View>
</TouchableOpacity>
</Card>
)}
/>
<Modal
transparent={true}
visible={this.state.show}
>
<View style={styles.modal}>
<View style={styles.inModal}>
<Button title='End' onPress={()=>{this.setState({show:false})}}/>
</View>
</View>
</Modal>
</View>
);}
}
this is the code I'm currently working on I want the 'meal_data' in 'handlePress' to be displayed inside my modal 'meal_data' is the selected item from the flat list .
<Modal
transparent={true}
visible={this.state.show}
>
<View style={styles.modal}>
<View style={styles.inModal}>
<Button title='End' onPress={()=>{this.setState({show:false})}}/>
</View>
</View>
</Modal>
I want to display it in here above the button

Change these lines of code:
Change: <TouchableOpacity onPress={(_item)=>{handlePress(item)}}>
To
<TouchableOpacity onPress={() => this.handlePress(item)}>
Delete this code inside render():
const handlePress = (meal_data) =>{
this.setState({show: true});
this.setState({selectedMeal:meal_data});
console.log(meal_data)
}
And put this code above render() medthod instead:
handlePress = (meal_data) =>{
this.setState({show: true, selectedMeal: meal_data});
console.log(meal_data)
}
Inside state
this.state = {
loaded:false,
show:false,
key:''
selectedMeal: null // Add this property
}}
After that, you'll be able to access selectedMeal inside your Modal.
Put this code inside the Modal (or somewhere else)
{this.state.selectedMeal && (
<View>
<Text>{this.state.selectedMeal.title}</Text>
</View>
)}

First of declare your handlePress outside of render method. Other thing is that this.setState() is Async so, first set you data then show the modal. Your final code should look like this :
import React, { Component } from 'react';
import { View, Text, Image, StyleSheet, Modal, Button } from 'react-native';
import { FlatList, TouchableOpacity, ScrollView } from 'react-native-gesture-handler';
import Card from '../shared/card';
import { AppLoading } from 'expo';
import * as Font from 'expo-font';
export default class MealSearch extends Component {
constructor(props) {
super(props)
this.state = {
loaded: false,
show: false,
key: ''
}
}
handlePress = (meal_data) => {
this.setState({ selectedMeal: meal_data }, () => {
this.setState({ show: true });
});
console.log(meal_data)
}
render() {
const meal = [
{ title: 'My hero Academia', img: { uri: 'https://i.cdn.turner.com/adultswim/big/img/2018/05/10/MHA_Header.png' }, body: 'Rating : 4.5/5', id: '1' },
{ title: 'Naruto', img: { uri: 'https://store-images.s-microsoft.com/image/apps.15041.71343510227343465.377174a9-abc8-4da3-aaa6-8874fdb9e2f5.00fc0a9e-295e-40ca-a391-58ed9f83e9a0?mode=scale&q=90&h=1080&w=1920&background=%23FFFFFF' }, body: 'Rating : 5/5', id: '2' },
{ title: 'Attack On Titan', img: { uri: 'https://www.denofgeek.com/wp-content/uploads/2013/12/attack-on-titan-main.jpg?fit=640%2C380' }, body: 'Rating : 4.5/5', id: '3' },
{ title: 'Fate: Unlimited Blade Works', img: { uri: 'https://derf9v1xhwwx1.cloudfront.net/image/upload/c_fill,q_60,h_750,w_1920/oth/FunimationStoreFront/2066564/Japanese/2066564_Japanese_ShowDetailHeaderDesktop_496a6d81-27db-e911-82a8-dd291e252010.jpg' }, body: 'Rating : 4.5/5', id: '4' }
]
return (
<View style={styles.view} >
<FlatList
keyExtractor={item => item.id}
data={meal}
renderItem={({ item }) => (
<Card>
<TouchableOpacity onPress={() => { this.handlePress(item) }}>
<View style={styles.mealItem}>
<Image style={{ width: 300, height: 150 }} resizeMode={'contain'} source={item.img} marginLeft={30} />
<View style={styles.descrip}>
<Text style={styles.rating}>{item.title}</Text>
<Text style={styles.name}>{item.body}</Text>
</View>
</View>
</TouchableOpacity>
</Card>
)}
/>
<Modal
transparent={true}
visible={this.state.show}
>
<View style={styles.modal}>
<View style={styles.inModal}>
<Button title='End' onPress={() => { this.setState({ show: false }) }} />
</View>
</View>
</Modal>
</View>
);
}
}

Related

react native table components

Hello there, I world be extremely grateful if someone could help me with this problem. I am new to react native and I wanted to the data inside the table instead of having its text because I think it will look better.I have stuck with this problem for a quite while and I couldnt find any sources to deal with this problem. Hope you can help me. Here is my code:
import React, { useState } from 'react';
import {View, Dimensions, Alert, Text, StyleSheet, Button, ScrollView, Pressable, ToastAndroid } from 'react-native';
import DestinationSearch from '../../components/DestinationSearch'
import { useRoute, useNavigation, useFocusEffect, useIsFocused } from '#react-navigation/native';
import { useEffect } from 'react';
import AsyncStorage from '#react-native-async-storage/async-storage';
import moment from 'moment';
import { Table, Row, Rows } from 'react-native-table-component';
const MapScreen = (props) => {
async function loopBusPressed (loopBusId) {
const locations = JSON.parse(await AsyncStorage.getItem('locations'));
const loopBusesCurrentLocation = JSON.parse(await AsyncStorage.getItem('loopBusesCurrentLocation'));
const loopBus = loopBusesCurrentLocation.find(bus => bus.id == loopBusId);
const loopBusLocation = locations.find(loc => loc.id == loopBus.loopBusLocationId)
const mockUserLocation = JSON.parse(await AsyncStorage.getItem('mockUserLocation'));
setloopBusLocation(loopBusLocation)
setmockUserLocation(mockUserLocation)
setCoordinates(
[
loopBusLocation.coordinates,
mockUserLocation.coordinates
]
)
setSelectedLoopBus(loopBusId)
const arrivalDetails = [];
const filteredLoopBusLocations = locations.filter(loc => loc.loopBusId == loopBusId)
filteredLoopBusLocations.forEach(loc => {
const currentBusStopNum = loopBusLocation.stopNumber
const destStopNum = loc.stopNumber
let calculatedArrival;
let aggMinutes = 0;
let includedLocations;
if (currentBusStopNum > destStopNum) {
includedLocations = filteredLoopBusLocations.filter(loc => loc.stopNumber > currentBusStopNum || loc.stopNumber <= destStopNum)
includedLocations.forEach(loc => {
aggMinutes += loc.durationInto
})
calculatedArrival = moment(new Date()).add(aggMinutes, 'm').format('LT')
} else if (currentBusStopNum < destStopNum) {
includedLocations = filteredLoopBusLocations.filter(loc => loc.stopNumber > currentBusStopNum && loc.stopNumber <= destStopNum )
includedLocations.forEach(loc => {
aggMinutes += loc.durationInto
})
calculatedArrival = moment(new Date()).add(aggMinutes, 'm').format('LT')
} else {
filteredLoopBusLocations.forEach(loc => {
aggMinutes += loc.durationInto
})
calculatedArrival = moment(new Date()).add(aggMinutes, 'm').format('LT')
}
arrivalDetails.push({
stopNumber: loc.stopNumber,
location: loc.location,
arrival: calculatedArrival
})
})
setArrivalDetails(arrivalDetails)
console.log(arrivalDetails)
}
const [coordinates, setCoordinates] = useState([]);
const [loopBusLocation, setloopBusLocation] = useState({});
const [mockUserLocation, setmockUserLocation] = useState({});
const [selectedLoopBus, setSelectedLoopBus] = useState(1);
const [arrivalDetails, setArrivalDetails] = useState([]);
useEffect(() => {
loopBusPressed(1)
}, []);
// const selectedItem = {
// title: 'Selected item title',
// description: 'Secondary long descriptive text ...',
// };
const header = ['Bus Stop', 'Location', 'Time']
const data = [
['gfg1', 'gfg2', 'gfg3'],
['gfg4', 'gfg5', 'gfg6'],
['gfg7', 'gfg8', 'gfg9']
]
const isFocused = useIsFocused();
alert(isFocused);
useFocusEffect(
React.useCallback(() => {
return () => null;
}, [])
);
return (
<View style={{display: 'flex', justifyContent: 'space-between'}}>
<View style={{height: Dimensions.get('window').height - 400}}>
<DestinationSearch coordinates={coordinates} />
</View>
<View style={{height: 400}}>
<ScrollView>
<View style={styles.page}>
<View style={styles.container}>
{/* TODO */}
<Pressable
style ={styles.button}
onPress={() => loopBusPressed(1)}
>
<Text style ={styles.buttonText}>Loop Bus 1</Text>
</Pressable>
{/* TODO */}
<Pressable
style ={styles.button}
onPress={() => loopBusPressed(2)}
>
<Text style ={styles.buttonText}>Loop Bus 2</Text>
</Pressable>
</View>
<View style={styles.page}>
{/* TODO */}
<Text style={styles.subTitle}>LOOP BUS {selectedLoopBus} TRANSIT DETAILS</Text>
{/* TODO */}
<Text style={styles.txt}>Current bus location: </Text>
<Text style={styles.description}>{loopBusLocation.location} </Text>
<View style={styles.separator}/>
{/* TODO */}
<Text style={styles.txt}>Your location: </Text>
<Text style={styles.description}>{mockUserLocation.location} </Text>
<View style={styles.separator}/>
</View>
<View style={styles.page}>
{
arrivalDetails.map((details, index) => {
return <Text>(Stop {details.stopNumber}) --- ({details.location}) --- ({details.arrival})</Text>
})
}
</View>
<View style={styles.page}>
<Table borderStyle={{ borderWidth: 2,
borderColor: '#c8e1ff' }}>
<Row data={header} />
<Rows data={data} />
</Table>
</View>
</View>
</ScrollView>
</View>
</View>
);
};
export default MapScreen;

onPress() not working on expo v42.0.0. Using TouchableOpacity for the rounded button

I used useState hook. onSubmitEditing i.e. pressing enter the command setTmpItem should run and should set the value of inputBox in the variable tmpItem.
addSubject prop passed is also a hook, which can be seen in 2nd code(app.js)
But when I press the RoundedButton, it is not console logging neither 1 nor 2 and also addSubject(tmpItem) not working.
Focus.js below
import React, { useState } from 'react';
import { View, StyleSheet, Text } from 'react-native';
import { TextInput } from 'react-native-paper';
import { RoundedButton } from '../../components/RoundedButton';
export const Focus = ({ addSubject }) => {
const [tmpItem, setTmpItem] = useState(null);
return (
<View style={styles.container}>
<View>
<Text> What would you like to focus on? </Text>
<View>
<TextInput
onSubmitEditing={({ nativeEvent: { text } }) => {
setTmpItem(text);
}}
/>
<RoundedButton
size={50}
title="+"
onPress={() => {
console.log("1");
addSubject(tmpItem);
console.log("2");
}}
/>
</View>
</View>
</View>
);
};
App.js below
//App.js is the central point to glue everything
import React, { useState } from 'react';
import { View, StyleSheet, Text } from 'react-native';
import { Focus } from './src/features/focus/Focus';
export default function App() {
const [focusSubject, setFocusSubject] = useState(null);
return (
<View>
{focusSubject ? (
<Text>Where am I going to build a timer</Text>
) : (
<Focus addSubject = {setFocusSubject}/>
)}
<Text>{focusSubject}</Text>
</View>
);
}
RoundedButton.js below
import React from 'react';
import { TouchableOpacity, View, Text, StyleSheet } from 'react-native';
export const RoundedButton = ({
style = {},
textStyle = {},
size = 125,
...props
}) => {
return (
<TouchableOpacity>
<Text>{props.title}</Text>
</TouchableOpacity>
);
};
You need to handle your TextInput for Focus.js by passing the value and onChangeText props in TextInput component like:
export const Focus = ({ addSubject }) => {
const [tmpItem, setTmpItem] = useState(null);
const onSubmit = () => {
//and handle this onSubmit function the way you want to
//or pass the addSubject props
addSubject(tmpItem);
}
return (
<View style={styles.container}>
<View>
<Text> What would you like to focus on? </Text>
<View>
<TextInput
onChangeText={setTmpItem}
value={tmpItem}
onSubmitEditing={() => onSubmit()}
/>
<RoundedButton
size={50}
title="+"
onPress={() => {
addSubject(tmpItem);
}}
/>
</View>
</View>
</View>
);
};
Also, the reason why console.log not working in RoundedButton is, you're not passing that onPress prop to your TouchableOpacity of RoundedButton. In RoundedButton.js do it like this:
import React from 'react';
import { TouchableOpacity, View, Text, StyleSheet } from 'react-native';
export const RoundedButton = ({
style = {},
textStyle = {},
size = 125,
...props
}) => {
return (
<TouchableOpacity onPress={props.onPress}>
<Text>{props.title}</Text>
</TouchableOpacity>
);
};
props.onPress is what you're missing.
Hope this works for you.

react native navigate to screen from function

I'm trying to move through screens using React Navigation, the problem lies in the nested return that i use to dynamically render a set of items and doesn't let me use an arrow function to directly navigate, so i have to implement this on a function. My question here is, how do i do that? As far as my internet research went you can only push a new screen after a dialog alert shows up, i don't want that.
I'm attaching the code:
var Dimensions = require('Dimensions');
var {width,height} = Dimensions.get('window');
import React, {Component} from 'react';
import {
View,
Text,
StyleSheet,
TouchableOpacity,
Image
} from 'react-native';
import Pie from 'react-native-pie';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import NaviBarView from './../Commons/NaviBar'
import actions from '../../Redux/actions'
class Main extends Component {
constructor(props){
super(props);
this.state={
cargando:true,
cryptoCurrencyValues:{}
}
this.onNextPress = this.onNextPress.bind(this);
this.renderItems = this.renderItems.bind(this);
}
static getDerivedStateFromProps(nextProps,prevState){
console.warn('Positivo', Object.keys(nextProps.cryptoCurrencyValues).length)
if (Object.keys(nextProps.cryptoCurrencyValues).length !== 0){
}else{
console.warn('Negativo')
}
return null;
}
onNextPress(){
**//HERE I WANT TO CALL NAVIGATE TO MOVE TO ANOTHER SCREEN**
}
componentDidMount(){
console.warn('esto una vez')
this.props.actions.getCryptoValues();
this.setState({cargando:true})
}
renderItems(){
var self = this;
return listData.map(function(cryptoValue,i){
return(
<View style={styles.itemContainer} key={i}>
<View style={{alignSelf:'center',backgroundColor:'transparent', marginLeft:10}}>
<Image source={cryptoValue.img} style={{width:width*0.095, height:height*0.050}} resizeMode={'stretch'}/>
</View>
<View style={{marginLeft:10}}>
<View style={{alignSelf:'flex-start',marginTop:15}}>
<Text style={{color:'#ffffff',fontSize:18,fontWeight: 'bold'}}>{cryptoValue.name}</Text>
</View>
<View style={{alignSelf:'flex-start',marginBottom:10}}>
<Text style={{color:'#6e6e6e',fontSize:18}}>{cryptoValue.desc}</Text>
</View>
</View>
<View style={{marginLeft:40}}>
<View style={{alignSelf:'flex-start',marginTop:15}}>
<Text style={{color:'#ffffff',fontSize:18}}>{cryptoValue.price}</Text>
</View>
<View style={{alignSelf:'flex-start',marginBottom:10}}>
<Text style={{color:'#6e6e6e',fontSize:18}}>{cryptoValue.currency}</Text>
</View>
</View>
<View style={{alignSelf:'center',backgroundColor:'transparent', marginLeft:50}}>
<TouchableOpacity onPress={() => self.onNextPress()} style={{alignSelf:'center',backgroundColor:'transparent'}}>
<Image source={require('./../../img/next.png')} style={{width:width*0.035, height:height*0.032}} resizeMode={'stretch'}/>
</TouchableOpacity>
</View>
</View>
);
});
}
render(){
return(
<View style={styles.container}>
<View>
<NaviBarView/>
</View>
<View style={styles.cardContainer}>
<View style={{marginTop:10,flexDirection: 'row',marginTop:10,marginLeft:10,alignItems:'stretch'}}>
<Image source={require('./../../img/pie-chart.png')} resizeMode={'stretch'} style={{width:width*0.095, height:height*0.055}}/>
<Text style={{fontSize:20,color:'#ffffff',fontWeight:'bold',marginLeft:15,alignSelf:'center'}}>STATUS</Text>
<TouchableOpacity style={{marginLeft:230,alignSelf:'center'}}>
<Image source={require('./../../img/reload.png')} resizeMode={'stretch'} style={{width:width*0.065, height:height*0.035}}/>
</TouchableOpacity>
</View>
<View style={{alignSelf:'flex-start',marginTop:50}}>
<Pie
radius={100}
innerRadius={97}
series={[10, 20, 30, 40]}
colors={['#f00', '#0f0', '#00f', '#ff0']}
/>
</View>
</View>
{this.renderItems()}
</View>
);
}
}
const listData = [
{_id:1,name:'Bitcoin',desc:'Billetera BTC',price:'$141,403.22',currency:'BTC: $11.673,50',img:require('./../../img/bitcoin.png')},
{_id:2,name:'Ethereum',desc:'Billetera ETH',price:'$20200,50',currency:'ETH: $863,40',img:require('./../../img/ethereum.png')},
{_id:3,name:'NEO',desc:'Billetera NEO',price:'$40.401',currency:'NEO: $118,02',img:require('./../../img/neo.png')},
];
const styles = new StyleSheet.create({
container:{
flex:1,
backgroundColor: '#0d0d0d',
flexDirection: 'column',
position:'relative',
},
cardContainer:{
backgroundColor:'#1a1a1a',
marginTop: 7,
marginBottom:7,
marginLeft:7,
marginRight:7,
height:height*0.50,
width:width,
justifyContent: 'flex-start'
},
itemContainer:{
flexDirection: 'row',
backgroundColor:'#1a1a1a',
width:width,
height:height*0.115,
marginLeft:7,
marginRight:7,
marginBottom:7,
justifyContent: 'flex-start'
},
})
function mapStateToProps (state,props) {
return {cryptoCurrencyValues: state.cryptocurrencyValues,
}
}
function mapDispatchToProps (dispatch) {
return {
actions: bindActionCreators(actions, dispatch)
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Main);
You can use Stack Navigator here which is very easy to navigate from one screen to another and as well as in function too...
First.
Install library :-
npm install --save react-navigation
Then use it in your class by using import :-
import {StackNavigator} from 'react-navigation';
export that class
export default Project = StackNavigator(
{
xyz: { screen: xyz },
});
After that navigating using function:-
onNextPress=()=>
{
this.props.navigation.navigate('xyz');
}
Hope.it will helps you .
Thanx!
I was not passing the navigation prop when defining my RootStack:
import React, {Component} from 'react'
import {
AppRegistry,
StyleSheet,
Text,
View,
} from 'react-native';
import createStore from './../../Redux/store';
import {StackNavigator} from 'react-navigation';
import { Provider } from 'react-redux';
import MainView from '../Main/Main';
import MainSecondLvlView from '../Main/MainSecondLvl';
import BalanceView from './../Charts/BalanceView'
import MenuView from './Menu'
const store = createStore();
const RootStack = StackNavigator({
Main: { screen: MainView },
MainSecondLvl: { screen: MainSecondLvlView},
Menu:{ screen: MenuView }
},
{
initialRouteName: 'Main',
headerMode: 'none',
});
export default class App extends Component {
render(){
return(
<Provider store={store}>
<RootStack navigation={this.props.navigation}/>
</Provider>
);
}
}

How to navigate from one screen to another scree in react native>?

Explanation: I have working with react native in android.I started with the login screen and pass the parameter to another screen using API success call.i used a StackNavigation to navigate the screen. After successful login it will move to another screen with parameter.
Issue: API call is success but the navigation screen is not changed. fire an error like undefined is not a function (evaluating '_this.props.navigator('SecondScreen')')
I have post my all code over here.
index.android.js
// This is the entry point of an application. It will cal the first App.js.
/**
* Sample React Native App
* https://github.com/facebook/react-native
* #flow
*/
import React,{Component} from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View
} from 'react-native';
import App from './src/components/App';
import SecondScreen from './src/components/SecondScreen';
import {StackNavigator} from 'react-navigation';
export default class reactNavigationSample extends Component{
render(){
const {navigation} =this.props;
return(
<App navigation ={navigation}/>
);
}
}
const SampleApp = StackNavigator({
Home:{screen:App},
SecondScreen:{screen: SecondScreen}
});
AppRegistry.registerComponent('AwesomeProject', () => SampleApp);
App.js
// This file have a UI which is two TextInput and Button. When i click on button it will call the login method and the login method will call the API with the possible credentials of the login API. After successfull login it should move to another screen.
export default class App extends Component{
static navigationOptions ={
title : 'Home Screen',
}
constructor(props){
super(props);
navigate = props.navigation,
this.state={email:'',password:'',device_token:'',device_type:''};
}
login = () => {
fetch('http://span.mobiosolutions.com/api/v1/login',{
method:'POST',
headers:{
'Accept':'application/json',
'Content-Type':'application/json',
},
body:JSON.stringify({
email: this.state.username,
password: this.state.password,
device_token: 'aajdflkajdjfajdflkj',
device_type: '1'
})
})
.then((response) => response.json())
.then((res) => {
if(res.statusCode === 1){
console.log(res);
var username=res.message;
AsyncStorage.setItem('username',username);
this.props.navigator('SecondScreen')
}else{
alert(res.message);
}
})
.done();
}
render(){
const {navigate} = this.props.navigation;
return(
<View style={styles.container}>
<Image source={require('../img/background.jpg')} style={styles.backgroundImage}>
<View style={styles.content}>
<Text style={styles.logo}>- NATIVE -</Text>
<View style={styles.inputContainer}>
<TextInput underlineColorAndroid='transparent' style={styles.input}
onChangeText={(username) => this.setState({username})}
value={this.state.username}
placeholder='username' />
<TextInput secureTextEntry={true} underlineColorAndroid='transparent' style={styles.input}
onChangeText={(password) => this.setState({password})}
value={this.state.password} placeholder='password'/>
{/*<Button*/}
{/*onPress={() => navigate('SecondScreen')}*/}
{/*title="Login"/>*/}
<Button
onPress={this.login}
title="Login"/>
</View>
</View>
</Image>
</View>
)
}
}
const styles=StyleSheet.create({
container:{
flex:1,
justifyContent:'center',
alignItems:'center',
backgroundColor:'#F5FCFF',
},
backgroundImage:{
flex:1,
alignSelf:'stretch',
width:null,
justifyContent:'center',
},
welcome:{
fontSize:20,
textAlign:'center',
margin:10,
},
instructions:{
textAlign:'center',
color:'#333333',
marginBottom:5,
},
content:{
alignItems:'center',
},
logo:{
color:'white',
fontSize:40,
fontStyle:'italic',
fontWeight:'bold',
textShadowColor:'#252525',
textShadowOffset:{width:2,height:2},
textShadowRadius:15,
marginBottom:20,
},
inputContainer:{
margin:20,
marginBottom:0,
padding:20,
paddingBottom:10,
alignSelf:'stretch',
borderWidth:1,
borderColor:'#fff',
backgroundColor:'rgba(255,255,255,0.2)',
},
input:{
fontSize:16,
height:40,
padding:10,
marginBottom:10,
backgroundColor:'rgba(255,255,255,1)',
},
});
SecondScreen.js
const SecondScreen = () => {
return(
<View style={styles.container}>
<Text style={styles.welcome}>
THIS IS THE SECOND SCREEN.
</Text>
</View>
);
}
const styles=StyleSheet.create({
container:{
flex:1,
justifyContent:'center',
alignItems:'center',
backgroundColor:'#F5FCFF',
},
welcome:{
fontSize:20,
textAlign:'center',
margin:10,
},
instructions:{
textAlign:'center',
color:'#333333',
marginBottom:5,
},
});
SecondScreen.navigationOptions ={
title: 'Second Screen Title'
}
export default SecondScreen
Please help me solved out this issue in React Native. Thank you in advance.
There is a typo in the line in App.js
this.props.navigator('SecondScreen')
It should be
this.props.navigation.navigate('SecondScreen')

React-native : attempt Attempted to redefine property 'color'

This is my index.android.js , after navigate to login.js, it show the error.
How can i find where the error occur?
I run eslint , but no error result.
/**
* Sample React Native App
* https://github.com/facebook/react-native
*/
'use strict';
var React = require('react-native');
var {
AppRegistry,
Component,
Navigator,
} = React;
var Login = require('./Login');
class WOMGrocery extends Component {
constructor(props) {
super(props);
this.state = {isNavHidden: true};
}
render() {
return (
<React.Navigator
// style={styles.container}
initialRoute={{
title: 'WOMGrocery',
component: Login,
}}
navigationBarHidden={this.state.isNavHidden}
/>
);
}
}
AppRegistry.registerComponent('WOMGrocery', () => WOMGrocery);
i enclosed my login.js as well. I have no idea where the redefined 'color' come from.
'use strict';
var React = require('react-native');
var Home = require('./Home');
var RegisterStep1 = require('./RegisterStep1');
var Config = require('./Config');
var Modal = require('react-native-modalbox');
var {
StyleSheet,
View,
PixelRatio,
PushNotificationIOS,
NavigatorIOS,
AlertIOS,
Navigator,
Text,
TextInput,
Image,
TouchableHighlight,
Component
} = React;
var Button = React.createClass({
render: function() {
return (
<TouchableHighlight
underlayColor={'white'}
style={styles.button}
onPress={this.props.onPress}>
<Text style={styles.buttonLabel}>
{this.props.label}
</Text>
</TouchableHighlight>
);
}
});
class Login extends Component {
constructor(props) {
super(props);
this.state = {
// usernameString: '***#yahoo.com',
// passwordString: '***',
usernameString: '***#gmail.com',
passwordString: '***',
// usernameString: '***#gmail.com',
// passwordString: '***',
// usernameString: '',
// passwordString: '',
email_retrieve: '',
};
}
componentWillMount() {
PushNotificationIOS.addEventListener('notification', this._onNotification);
}
componentWillUnmount() {
PushNotificationIOS.removeEventListener('notification', this._onNotification);
}
_sendNotification() {
require('RCTDeviceEventEmitter').emit('remoteNotificationReceived', {
aps: {
alert: 'Sample notificationion',
badge: '+1',
sound: 'default',
category: 'REACT_NATIVE'
},
});
}
_onNotification(notification) {
AlertIOS.alert(
'Notification Received',
'Alert message: ' + notification.getMessage(),
[{
text: 'Dismiss',
onPress: null,
}]
);
}
openModal1(id) {
this.refs.modal1.open();
}
openModal2(id) {
this.refs.modal2.open();
}
openModal3(id) {
this.refs.modal3.open();
}
openModal4(id) {
this.refs.modal4.open();
}
openModal5(id) {
this.setState({isOpen: true});
}
openModal6(id) {
this.refs.modal6.open();
}
openModal7(id) {
this.refs.modal7.open();
}
closeModal3(id) {
this.refs.modal3.close();
}
closeModal4(id) {
this.refs.modal4.close();
}
closeModal5(id) {
this.setState({isOpen: false});
}
closeModal6(id) {
this.refs.modal6.close();
}
closeModal7(id) {
this.refs.modal7.close();
}
ForgotPwd() {
var fURL = Config.server + '/submitForgotPassword/' + this.state.email_retrieve + '/Grocery';
fetch(fURL)
.then((response) => response.json())
.then((responseText) => {
// console.log(responseText);
this.closeModal3.bind(this);
})
.catch((error) => {
console.warn("a:"+error);
alert(error);
});
}
Home() {
this.props.navigator.push({
title: 'Home',
component: Home,
passProps: {},
});
this.setState({
isNavHidden: false
});
}
RegisterStep1Page() {
this.props.navigator.push({
title: 'Results',
component: RegisterStep1,
passProps: {},
});
}
onEmailRetrieveChanged(event) {
this.setState({ email_retrieve: event.nativeEvent.text });
}
onUsernameTextChanged(event) {
this.setState({ usernameString: event.nativeEvent.text });
}
onPasswordTextChanged(event) {
this.setState({ passwordString: event.nativeEvent.text });
}
onHomePressed() {
var uStr = this.state.usernameString;
var pStr = this.state.passwordString;
if (uStr.length>1) {
if (pStr.length>1) {
this._executeHome();
} else {
this.openModal7();
}
} else {
this.openModal6();
}
}
_handleHomeResponse(responseText, cCode) {
this.props.navigator.push({
title: 'Home',
component: Home,
passProps: {
listings: responseText,
cCode: cCode,
}
});
}
_executeHome() {
var fURL = Config.server + '/login/' + this.state.usernameString + '/' + this.state.passwordString + '/Grocery';
fetch(fURL)
.then((response) => response.json())
.then((responseText) => {
if (responseText.myArrayList[0].myHashMap.StatusCode=="200") {
var cCode = responseText.myArrayList[0].myHashMap.Code;
var fURL2 = Config.server + '/getCustomerCart/' + cCode;
fetch(fURL2)
.then((response) => response.json())
.then((responseText) => {
var arr_length = +responseText.myArrayList.length - 1;
this._handleHomeResponse(responseText.myArrayList[arr_length].myArrayList[0], cCode);
})
.catch((error) => {
console.warn(error);
});
} else {
this.openModal4();
// alert("Incorrect username or password");
}
})
.catch((error) => {
console.warn("a:"+error);
alert(error);
});
}
render() {
return (
<View style={styles.container}>
<View style={styles.imageContainer}>
<Image source={require('image!fruit')} style={styles.fruit} />
</View>
<View style={styles.imageLogo2}>
<Image resizeMode="contain" source={require('image!logo2')} style={styles.logo2} />
</View>
<View style={styles.imageLogo3}>
<Image resizeMode="contain" source={require('image!logo3')} style={styles.logo3} />
</View>
<Button
style={styles.btn2}
onPress={this._sendNotification}
/>
<Image resizeMode="contain" source={require('image!register_at2')} style={styles.register_at2} />
<Image resizeMode="contain" source={require('image!register_pw2')} style={styles.register_pw2} />
<TextInput style={styles.inputText_email} placeholder=' Email' placeholderTextColor='white' onChange={this.onUsernameTextChanged.bind(this)}/>
<View style={styles.thinLine}></View>
<View style={styles.thinLine2}></View>
<TextInput style={styles.inputText_password} placeholder=' Password' placeholderTextColor='white' onChange={this.onPasswordTextChanged.bind(this)} secureTextEntry={true} />
<Text style={styles.copyrightStyle}>
Copyright (C) 2016 www.ocmeritmall.com
</Text>
<TouchableHighlight style={styles.buttonRegister} onPress={this.RegisterStep1Page.bind(this)} underlayColor='transprance'>
<Text style={styles.buttonText2}>New here? Create an account ></Text>
</TouchableHighlight>
<TouchableHighlight style={styles.buttonLogin} onPress={this.onHomePressed.bind(this)} underlayColor='transprance'>
<Image resizeMode="contain" source={require('image!member_login')} style={styles.member_login} />
</TouchableHighlight>
<Text style={styles.instructions}>
All rights reserved (version 1.2.19)
</Text>
<TouchableHighlight style={styles.buttonForgetPwd} underlayColor='transprance' onPress={this.openModal3.bind(this)}>
<Text style={styles.buttonText}>Cannot access your account? ></Text>
</TouchableHighlight>
<Modal style={[styles.modal, styles.modal1]} ref={"modal1"} onClosed={this.onClose} onOpened={this.onOpen} onClosingState={this.onClosingState}>
<Text style={styles.text}>You are not in the latest app version</Text>
<Text style={styles.text2}>Press OK to download the latest app version</Text>
</Modal>
<Modal style={[styles.modal, styles.modal1]} ref={"modal2"} onClosed={this.onClose} onOpened={this.onOpen} onClosingState={this.onClosingState}>
<Text style={styles.text}>Whoops! You Have No Internet</Text>
<Text style={styles.text2}>Please check your network setting</Text>
</Modal>
<Modal style={[styles.modal, styles.modal1]} ref={"modal3"} onClosed={this.onClose} onOpened={this.onOpen} onClosingState={this.onClosingState}>
<Text style={styles.text3}>Please Key In Your Registered Email</Text>
<TextInput style={styles.inputText_email_retrieve} placeholder=' Registered Email Address' onChange={this.onEmailRetrieveChanged.bind(this)} />
<TouchableHighlight style={styles.wrapperButtonOk} underlayColor='#FFAB0A' onPress={this.ForgotPwd.bind(this)}>
<Image source={require('image!buttonOk')} style={styles.buttonOk} />
</TouchableHighlight>
<TouchableHighlight style={styles.wrapperButtonCancel} underlayColor='#FFAB0A' onPress={this.closeModal3.bind(this)}>
<Image resizeMode="contain" source={require('image!buttonCancel')} style={styles.buttonCancel} />
</TouchableHighlight>
</Modal>
<Modal style={[styles.modal, styles.modal1]} ref={"modal4"} onClosed={this.onClose} onOpened={this.onOpen} onClosingState={this.onClosingState}>
<Text style={styles.text}>Incorrect username or password!</Text>
<Text style={styles.text2}>No space bar allow in enter login</Text>
<View style={styles.imagePassword}>
<Image source={require('image!pop_password')} style={styles.pop_password} />
</View>
<TouchableHighlight style={styles.wrapperButtonOk} underlayColor='#FFAB0A' onPress={this.closeModal4.bind(this)}>
<Image source={require('image!buttonOk')} style={styles.buttonOk} />
</TouchableHighlight>
<TouchableHighlight style={styles.wrapperButtonCancel} underlayColor='transprance' onPress={this.closeModal4.bind(this)}>
<Image resizeMode="contain" source={require('image!buttonCancel')} style={styles.buttonCancel} />
</TouchableHighlight>
</Modal>
<Modal isOpen={this.state.isOpen} onClosed={this.closeModal5} style={[styles.modal, styles.modal4]} position={"center"}>
<Text style={styles.text}>Modal with backdrop content</Text>
</Modal>
<Modal style={[styles.modal, styles.modal1]} ref={"modal6"} onClosed={this.onClose} onOpened={this.onOpen} onClosingState={this.onClosingState}>
<Text style={styles.text}>Login Email Cannot Be Empty!</Text>
<Text style={styles.text2}>Please re-enter your login email</Text>
<View style={styles.imageEpassword}>
<Image source={require('image!pop_epassword')} style={styles.pop_epassword} />
</View>
<TouchableHighlight style={styles.wrapperButtonCancel} underlayColor='transprance' onPress={this.closeModal6.bind(this)}>
<Image resizeMode="contain" source={require('image!buttonCancel')} style={styles.buttonCancel} />
</TouchableHighlight>
<TouchableHighlight style={styles.wrapperButtonOk} underlayColor='#FFAB0A' onPress={this.closeModal6.bind(this)}>
<Image source={require('image!buttonOk')} style={styles.buttonOk} />
</TouchableHighlight>
</Modal>
<Modal style={[styles.modal, styles.modal1]} ref={"modal7"} onClosed={this.onClose} onOpened={this.onOpen} onClosingState={this.onClosingState}>
<Text style={styles.text}>Login Password Cannot Be Empty!</Text>
<Text style={styles.text2}>Please re-enter your password</Text>
<View style={styles.imageEpassword}>
<Image source={require('image!pop_epassword')} style={styles.pop_epassword} />
</View>
<TouchableHighlight style={styles.wrapperButtonCancel} underlayColor='transprance' onPress={this.closeModal7.bind(this)}>
<Image resizeMode="contain" source={require('image!buttonCancel')} style={styles.buttonCancel} />
</TouchableHighlight>
<TouchableHighlight style={styles.wrapperButtonOk} underlayColor='#FFAB0A' onPress={this.closeModal7.bind(this)}>
<Image source={require('image!buttonOk')} style={styles.buttonOk} />
</TouchableHighlight>
</Modal>
</View>
);
}
}
var styles = StyleSheet.create({
thinLine: {.......
Could it be that you have a duplicate color property in a style?

Categories

Resources