I'm getting an unexpected identifier error on the line fetchMovies() { in the following program:
/**
* Sample React Native App
* https://github.com/facebook/react-native
*/
'use strict';
var React = require('react-native'),
{
StyleSheet,
Component,
AppRegistry,
ListView,
View,
Text,
Image
} = React,
baseUrl = 'http://api.rottentomatoes.com/api/public/v1.0/lists/movies/in_theaters.json',
apiKey = '7waqfqbprs7pajbz28mqf6vz',
pageLimit = 25,
queryString = '?apikey=' + apiKey + '&page_limit=' + pageLimit,
url = baseUrl + queryString,
styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
backgroundColor: 'white',
},
rightContainer: {
flex: 1,
},
title: {
marginBottom: 8,
textAlign: 'center'
},
year: {
fontSize: 10,
textAlign: 'center'
},
thumbnail: {
width: 53,
height: 81
},
listView: {
paddingTop: 20,
backgroundColor: 'black'
}
})
class movieList extends Component{
getInitialState() {
return {
dataSource: new ListView.DataSource({
rowHasChanged: (row1, row2) => row1 !== row2
}),
loaded: false
}
},
fetchMovies() {
return fetch(url)
.then((response) => response.json())
.then((data) => data.movies)
},
componentDidMount() {
this.fetchMovies()
.then((movies) => {
this.setState({
dataSource: this.state.dataSource.cloneWithRows(movies),
loaded: true
})
})
.done()
},
getLoadingView() {
return (
<View style={styles.container}>
<Text>
Loading Movies...
</Text>
</View>
)
},
renderMovie(movie) {
if (!this.state.loaded) {
return this.getLoadingView()
}
return (
<View style={styles.container}>
<Image
source={{uri: movie.posters.thumbnail}}
style={styles.thumbnail}
/>
<View style={styles.rightContainer}>
<Text style={styles.title}>{movie.title}</Text>
<Text style={styles.year}>{movie.year}</Text>
</View>
</View>
)
},
render() {
return (
<ListView
dataSource={this.state.dataSource}
renderRow={this.renderMovie}
style={styles.listView}
/>
)
}
}
AppRegistry.registerComponent('movieList', () => movieList)
What am I doing wrong?
You're treating the class construct as though it were a series of comma-separated var-like function expressions, but that's not how class works. The method definitions in a class are more like function declarations, and you don't put commas after them, because they're not part of one big expression as the variable list after var is.
class movieList extends Component{
getInitialState() {
return {
dataSource: new ListView.DataSource({
rowHasChanged: (row1, row2) => row1 !== row2
}),
loaded: false
}
} // <=== No comma here
fetchMovies() {
// ...
}
// ...
}
Related
Hi I am new to react native i am facing this error TypeError:undefined is not an object (evaluating this.state.items)
Another problem is it is returning me the data in an array how do i display the data as a string
import React, { Component } from "react";
import {StyleSheet,View,ActivityIndicator,FlatList,Text,TouchableOpacity} from "react-native";
export default class Source extends React.Component {
static navigationOptions = ({ navigation }) => {
return {
title: "Source Listing",
headerStyle: {backgroundColor: "#fff"},
headerTitleStyle: {textAlign: "center",flex: 1}
};
};
constructor(props) {
super(props);
this.state = {
loading: false,
items:[]
};
this.fetchRequest=this.fetchRequest.bind.this
}
FlatListItemSeparator = () => {
return (
<View style={{
height: .5,
width:"100%",
backgroundColor:"rgba(0,0,0,0.5)",
}}
/>
);
}
componentDidMount()
{
fetchRequest();
}
renderItem=(data)=>
<TouchableOpacity style={styles.list}>
<Text style={styles.lightText}>{data.item.name}</Text>
<Text style={styles.lightText}>{data.item.email}</Text>
<Text style={styles.lightText}>{data.item.company.name}</Text>
</TouchableOpacity>
render(){
<FlatList
data= {this.state.dataSource}
ItemSeparatorComponent = {this.FlatListItemSeparator}
renderItem= {item=> this.renderItem(item)}
keyExtractor= {item=>item.id.toString()}
/>
fetchRequest()
{
const parseString = require('react-native-xml2js').parseString;
fetch('http://192.168.200.133/apptak_service/apptak.asmx/Get_Item_Master')
.then(response => response.text())
.then((response) => {
parseString(response, function (err, result) {
console.log(response)
});
}).catch((err) => {
console.log('fetch', err)
this.fetchdata();
})
if(this.state.loading){
return(
<View style={styles.loader}>
<ActivityIndicator size="large" color="#0c9"/>
</View>
)}}
return(
<View style={styles.container}>
</View>
)}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "#fff"
},
loader:{
flex: 1,
justifyContent: "center",
alignItems: "center",
backgroundColor: "#fff"
},
list:{
paddingVertical: 4,
margin: 5,
backgroundColor: "#fff"
}
});
Basically what i am trying to do is to get data from webservices and display the app on the screen
I know how to populate jSON data on FlatList and I have done that , but now here , I am populating data in between button and table data , In componentDidMount i am calling both function , first table create and then JSON call , Table data I am taking from QRCode scan from another screen and taking here .
import React, { Component } from 'react';
import { StyleSheet, View, ActivityIndicator, ScrollView } from 'react-native';
import { Table, Row, Rows } from 'react-native-table-component';
import {Button, Text, DatePicker, Item, Picker, Input,
Textarea,FlatList} from 'native-base';
export default class OpenApplianceIssue extends Component {
constructor(props) {
super(props);
this.state = {
// tableHead: ['Head', 'Head2', 'Head3', 'Head4'],
tableData: [], qrData: '', loading: false, selectedPriority: '',
selectedIssue: '', selectedReason: '', selectedTriedRestart: '',
selectedPowerLED: '', selectedBurning: '', selectedNoise: '',
AbcSdata : null, loading : true,
}
this.setDate = this.setDate.bind(this);
}
setDate(newDate) {
}
_loadInitialState = async () => {
const { navigation } = this.props;
const qdata = navigation.getParam('data', 'NA').split(',');
var len = qdata.length;
const tData = [];
console.log(len);
for(let i=0; i<len; i++)
{
var data = qdata[i].split(':');
const entry = []
entry.push(`${data[0]}`);
entry.push(`${data[1]}`);
tData.push(entry);
}
this.setState({tableData: tData } );
console.log(this.state.tableData);
this.setState({loading: true});
}
componentDidMount() {
this._loadInitialState().done();
// this.createViewGroup();
}
// componentDidMount() {
// this.createViewGroup();
// }
createViewGroup = async () => {
try {
const response = await fetch(
'http://Dsenze/userapi/sensor/viewsensor',
{
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
"password": 'admin',
"username": 'admin',
"startlimit":"0",
"valuelimit":"10",
}),
}
);
const responseJson = await response.json();
const { sensorData } = responseJson;
this.setState({
AbcSdata: sensorData,
loading: false,
});
} catch (e) {
console.error(e);
}
};
updateSearch = search => {
this.setState({ search });
};
keyExtractor = ({ id }) => id.toString();
keyExtractor = ({ inventory }) => inventory.toString();
renderItem = ({ item }) => (
<TouchableOpacity
style={styles.item}
activeOpacity={0.4}
onPress={() => {
this.clickedItemText(item);
}}>
<Text style={styles.buttonText}>Id {item.inventory}</Text>
<Text>Inv {item.inventory}</Text>
<Text>Sensor {item.inventory}</Text>
</TouchableOpacity>
);
onClickListener = (viewId) => {
if(viewId == 'tag')
{
this.props.navigation.navigate('AddSensors');
}}
render() {
const state = this.state;
const AbcSdata = this.state;
if(this.state.loading == false) {
return ( <ActivityIndicator size='large' style={{height:80}} /> )
}
else {
return (
<ScrollView style={styles.container}>
<Button full rounded light style={{backgroundColor: 'blue', justifyContent: 'center', alignItems: 'center'}}
onPress={() => this.onClickListener('tag')}>
<Text style={{color: 'white'}}>Add Sensors</Text>
</Button>
<View style={styles.container1}>
{this.state.loading ? (
<ActivityIndicator size="large" />
) :
(
<FlatList
AbcSdata={AbcSdata}
renderItem={this.renderItem}
keyExtractor={this.keyExtractor}
/>
)}
</View>
<View>
<Text
style={{alignSelf: 'center', fontWeight: 'bold', color: 'black'}} >
Inventory Details
</Text>
<Table borderStyle={{borderWidth: 2, borderColor: '#c8e1ff', padding:10,paddingBottom: 10}}>
<Rows data={state.tableData} textStyle={styles.text}/>
</Table>
</View>
</ScrollView>
)
}
}
}
const styles = StyleSheet.create({
container: { flex: 1, padding: 16, paddingTop: 30, backgroundColor: '#fff' },
head: { height: 40, backgroundColor: '#f1f8ff' },
text: { margin: 6 }
});
try this code ..
import React, { Component } from 'react';
import { View, Text, TextInput,
FooterTab,Button,TouchableOpacity, ScrollView, StyleSheet,
ActivityIndicator ,Header,FlatList} from 'react-native';
import {Icon} from 'native-base';
import { Table, Row, Rows } from 'react-native-table-component';
import { createStackNavigator } from 'react-navigation';
import { SearchBar } from 'react-native-elements';
export default class OpenApplianceIssue extends Component {
constructor() {
super();
this.state = {
AbcSdata: null,
loading: true,
search: '',
tableData: [], qrData: '', selectedPriority: '',
selectedIssue: '', selectedReason: '', selectedTriedRestart: '',
selectedPowerLED: '', selectedBurning: '', selectedNoise: '',
};
this.setDate = this.setDate.bind(this);
}
setDate(newDate) {
}
_loadInitialState = async () => {
const { navigation } = this.props;
const qdata = navigation.getParam('data', 'NA').split(',');
var len = qdata.length;
const tData = [];
console.log(len);
for(let i=0; i<len; i++)
{
var data = qdata[i].split(':');
const entry = []
entry.push(`${data[0]}`);
entry.push(`${data[1]}`);
tData.push(entry);
}
this.setState({tableData: tData } );
console.log(this.state.tableData);
this.setState({loading: true});
}
componentDidMount() {
this._loadInitialState().done();
this.createViewGroup();
}
createViewGroup = async () => {
try {
const response = await fetch(
'http:Dsenze/userapi/sensor/viewsensor',
{
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
"password": 'admin',
"username": 'admin',
"startlimit":"0",
"valuelimit":"10",
}),
}
);
const responseJson = await response.json();
const { sensorData } = responseJson;
this.setState({
AbcSdata: sensorData,
loading: false,
});
} catch (e) {
console.error(e);
}
};
updateSearch = search => {
this.setState({ search });
};
keyExtractor = ({ id }) => id.toString();
keyExtractor = ({ inventory }) => inventory.toString();
renderItem = ({ item }) => (
<TouchableOpacity
style={styles.item}
activeOpacity={0.4}
onPress={() => {
this.clickedItemText(item);
}}>
<Text style={styles.buttonText}>Id {item.id}</Text>
<Text>Hospital Name {item.inventory}</Text>
<Text>User {item.inventory}</Text>
<Text>Date {item.inventory}</Text>
</TouchableOpacity>
);
onClickListener = (viewId) => {
if(viewId == 'tag')
{
this.props.navigation.navigate('AddSensors');
}}
renderSeparator = () => {
return (
<View
style={{
height: 1,
width: "86%",
backgroundColor: "#CED0CE",
}}
/>
);
};
render() {
const { loading, AbcSdata } = this.state;
const state = this.state;
return (
<ScrollView>
<View style={styles.container1}>
<TouchableOpacity full rounded light style={{backgroundColor: 'blue', justifyContent: 'center', alignItems: 'center'}}
onPress={() => this.onClickListener('tag')}>
<Text style={{color: 'white'}}>Add Sensors</Text>
</TouchableOpacity>
</View>
<View style={styles.container1}>
{this.state.loading ? (
<ActivityIndicator size="large" />
) :
(
<FlatList
data={AbcSdata}
renderItem={this.renderItem}
keyExtractor={this.keyExtractor}
ItemSeparatorComponent={this.renderSeparator}
/>
)}
</View>
<View>
<Text
style={{alignSelf: 'center', fontWeight: 'bold', color: 'black'}} >
Inventory Details
</Text>
<Table borderStyle={{borderWidth: 2, borderColor: '#c8e1ff', padding:10,paddingBottom: 10}}>
<Rows data={state.tableData} textStyle={styles.text}/>
</Table>
</View>
</ScrollView>
);
}
}
const styles = StyleSheet.create(
{
container1:
{
flex: 1,
alignItems: 'stretch',
fontFamily: "vincHand",
color: 'blue'
},
header_footer_style:{
width: '100%',
height: 44,
backgroundColor: '#4169E1',
alignItems: 'center',
justifyContent: 'center',
color:'#ffffff',
},
Progressbar:{
justifyContent: 'center',
alignItems: 'center',
color: 'blue',
},
ListContainer :{
borderColor: '#48BBEC',
backgroundColor: '#000000',
color:'red',
alignSelf: 'stretch' ,
},
container2:
{
flex: 1,
justifyContent: 'center',
alignItems: 'stretch',
paddingHorizontal: 15
},
inputBox:{
width:300,
borderColor: '#48BBEC',
backgroundColor: '#F8F8FF',
borderRadius:25,
paddingHorizontal:16,
fontSize:16,
color:'#000000',
marginVertical:10,
},
button:{
width:300,
backgroundColor:'#4169E1',
borderRadius:25,
marginVertical:10,
paddingVertical:16
},
buttonText:{
fontSize:16,
fontWeight:'500',
color:'#ffffff',
textAlign:'center'
},
textStyle:{
fontSize:16,
fontWeight:'500',
color:'#ffffff',
textAlign:'center'
},
item:
{
padding: 15
},
text:
{
fontSize: 18
},
button:{
width:300,
backgroundColor:'#4169E1',
borderRadius:25,
marginVertical:10,
paddingVertical:16
},
buttonText:{
fontSize:16,
fontWeight:'500',
color:'red',
textAlign:'center'
},
separator:
{
height: 2,
backgroundColor: 'rgba(0,0,0,0.5)'
},
container: { flex: 1, padding: 16, paddingTop: 30, backgroundColor: '#fff' },
head: { height: 40, backgroundColor: '#f1f8ff' },
text: { margin: 6 }
});
In your FlatList component you are setting AbcSdata={AbcSdata}, while you should be setting the data prop:
<FlatList
data={AbcSdata}
renderItem={this.renderItem}
keyExtractor={this.keyExtractor}
/>
It could be because _loadInitialState in your componentDidMount is an async call and table is getting rendered initially with no data. You could try passing in some prop to refresh once you have data. Also, in the code you put here, all calls to createViewGroup() are commented out but the definition is still there. Not a big problem but still very confusing for someone looking into your code.
I have the following code in react native:
'use strict'
import React, { Component } from 'react';
import { AppRegistry, Animated, Dimensions, Easing, Image, Text, View, StyleSheet, TouchableOpacity, ScrollView } from 'react-native';
const categoryTwoLinks = [
{ label: 'Subcategory1' },
{ label: 'Subcategory2' },
{ label: 'Subcategory3' },
{ label: 'Subcategory4' },
{ label: 'Subcategory5' },
{ label: 'Subcategory6' },
]
const categoryTouts = [
{ image: require('./assets/images/image01.jpg'), title: 'Category1' },
{ image: require('./assets/images/image02.jpg'), title: 'Category2', links: categoryTwoLinks },
{ image: require('./assets/images/image03.jpg'), title: 'Category3' },
]
class Tout extends Component {
render() {
console.log('tout')
return (
<Image
source={this.props.image}
ratioGrow
alignItems='center'
style={{ alignItems: 'center', justifyContent: 'center' }}
>
<Text
style={{ color: 'white', fontSize: 24, backgroundColor: 'transparent', fontWeight: 'bold' }}
>
{this.props.title}
</Text>
</Image>
)
}
}
export default class scrollAccordion extends Component {
handleScroll = ({ nativeEvent: { contentOffset } }: Object) => {
const scrollY = contentOffset.y
this.scrollOffsetValue.setValue(scrollY)
}
setScrollRef = node => {
console.log('set scroll ref')
if (node) {
this.scrollRef = node
}
}
renderCategoryTouts = () => {
console.log('render category tout')
categoryTouts.map((tout, index) => {
return (
<Tout
key={tout.title}
{...tout}
scrollViewRef={this.state.scrollRef}
scrollOffset={this.scrollOffsetValue}
/>
)
})
}
render() {
console.log('render')
let categoryTouts = this.scrollRef ? this.renderCategoryTouts() : null
return (
<View style={styles.container}>
<ScrollView
scrollEventThrottle={1}
ref={this.setScrollRef}
onScroll={this.handleScroll}
>
<View>
{categoryTouts}
</View>
</ScrollView>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
paddingTop: 40,
backgroundColor: 'white',
},
toutText: {
color: 'white', backgroundColor: 'transparent', fontWeight: 'bold', fontSize: 24
}
});
AppRegistry.registerComponent('scrollAccordion', () => scrollAccordion);
which is not returning any content from the renderCategoryTouts function.
I know that initially, this.scrollRef is undefined, so the main render function will return {null} for the {categoryTouts} variable. But after the scrollRef is set, I need it to return the results of renderCategoryTouts. How do I get this to work?
In renderCategoryTouts function of yours you have a variable categoryTouts variabke. You have never declared a variable like that in this function so I assume it is a global variable.
renderCategoryTouts = () => {
categoryTouts.map((tout, index) => {
return (
<Tout
key={tout.title}
{...tout}
scrollViewRef={this.state.scrollRef}
scrollOffset={this.scrollOffsetValue}
/>
)
})
}
And in this function you're using this.state.scrollRef, this.scrollOffsetValue so you need to bind this function.(I suggest you do that in the constructor of class)
this.renderCategoryTouts = this.renderCategoryTouts.bind(this)
also in case this does not work full code would be very helpful
I have a key value array in my state containing booleans indicating the value of my switches.
When I trigger the Switch component, the value is correctly changed in my state but the value of my Switch stays the same. It's like the component is not updated. I did the exact same thing in another project and it is working there.
_changeValue(k) {
switchesValues[k] = !switchesValues[k]
this.setState({
switches: switchesValues
})
}
_renderEventRow(allergiesList) {
var k = allergiesList.key
return (
<View style={{flexDirection: 'row', height: 50, alignItems: 'center', paddingLeft: 10, borderBottomWidth: 0.5, borderColor: 'lightgray'}}>
<Text style={{flex: 1, color: '#5f5f5f'}}>{allergiesList.name}</Text>
<Switch style={{marginRight: 10}} value={this.state.switches[k]} onValueChange={() => this._changeValue(k)}/>
</View>
)
}
My list view :
var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 != r2})
constructor(props) {
super(props)
this.state = {
ds:[],
dataSource:ds,
switches: []
}
}
componentDidMount() {
this.setState({
dataSource: this.state.dataSource.cloneWithRows(this.state.ds),
})
this.findAllergies()
}
render() {
return(
<ListView
dataSource={this.state.dataSource}
renderRow={(rowData) => { return this._renderEventRow(rowData)}}
/>)}
)
}
findAllergies() {
var that = this
firebase.database().ref("allergies").on("value", (snap) => {
var items = [];
snap.forEach((child) => {
items.push({
name: child.val(),
key: child.key,
})
})
that.setState({
dataSource: that.state.dataSource.cloneWithRows(items),
});
})
}
Hi I have created a sample app to implement your requirement. Have a look at the below code.
import React, {Component} from 'react';
import {
AppRegistry,
Text,
View,
TouchableOpacity,
Switch,
ListView,
} from 'react-native';
var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 != r2});
export default class AwesomeProject extends Component {
constructor(props) {
super(props)
this.state = {
ds: [],
dataSource: ds,
switches: []
}
}
componentDidMount() {
let allergies = [];
this.switchesValues = [];
for (let i = 0; i <= 5; i++) {
allergies.push({
key: i,
name: 'Name ' + i,
});
this.switchesValues[i] = false;
}
this.setState({
dataSource: this.state.dataSource.cloneWithRows(allergies),
switches: this.switchesValues,
})
}
render() {
return (
<ListView
dataSource={this.state.dataSource}
renderRow={(rowData) => { return this._renderEventRow(rowData)}}
/>);
}
_changeValue(k) {
console.log('Status '+JSON.stringify(this.switchesValues))
this.switchesValues[k] = !this.switchesValues[k];
this.setState({
switches: this.switchesValues,
})
}
_renderEventRow(allergiesList) {
var k = allergiesList.key
return (
<View
style={{flexDirection: 'row', height: 50, alignItems: 'center', paddingLeft: 10, borderBottomWidth: 0.5, borderColor: 'lightgray'}}>
<Text style={{flex: 1, color: '#5f5f5f'}}>{allergiesList.name}</Text>
<Switch style={{marginRight: 10}} value={this.state.switches[k]}
onValueChange={() => this._changeValue(k)}/>
</View>
)
}
}
AppRegistry.registerComponent('AwesomeProject', () => AwesomeProject);
I am trying to follow the example (https://github.com/facebook/react-native/tree/master/Examples/UIExplorer/Navigator) on the react native site to set up my navigator, but I can't seem to get it to work. No matter what I seem to do, the GoogSignIn scene always comes up blank although it does hit both of my console.log points in the file. I have tried switching the starting point to a different scene in my app, but the same thing always happens. I assume this is something I did wrong in index.ios.js with my navigator, but I'm not sure what. Any help is much appreciated.
index.ios.js
'use strict';
var React = require('react-native');
var DataEntry = require('./app/DataEntry');
var PasswordView = require('./app/PasswordView');
var GoogSignIn = require('./app/GoogSignIn');
var {
AppRegistry,
Image,
StyleSheet,
Text,
View,
Navigator,
TouchableOpacity,
} = React;
class PasswordRecovery extends React.Component {
render() {
return (
<Navigator
ref={this._setNavigatorRef}
style={styles.container}
initialRoute={{id: 'GoogSignIn', name: 'Index'}}
renderScene={this.renderScene}
configureScene={(route) => {
if (route.sceneConfig) {
return route.sceneConfig;
}
return Navigator.SceneConfigs.FloatFromRight;
}} />
);
}
renderScene(route, navigator) {
switch (route.id) {
case 'GoogSignIn':
return <GoogSignIn navigator={navigator} />;
case 'DataEntry':
return <DataEntry navigator={navigator} />;
case 'PasswordView':
return <PasswordView navigator={navigator} />;
default:
return this.noRoute(navigator);
}
noRoute(navigator) {
return (
<View style={{flex: 1, alignItems: 'stretch', justifyContent: 'center'}}>
<TouchableOpacity style={{flex: 1, alignItems: 'center', justifyContent: 'center'}}
onPress={() => navigator.pop()}>
<Text style={{color: 'red', fontWeight: 'bold'}}>ERROR: NO ROUTE DETECTED</Text>
</TouchableOpacity>
</View>
);
}
_setNavigatorRef(navigator) {
if (navigator !== this._navigator) {
this._navigator = navigator;
if (navigator) {
var callback = (event) => {
console.log(
`TabBarExample: event ${event.type}`,
{
route: JSON.stringify(event.data.route),
target: event.target,
type: event.type,
}
);
};
// Observe focus change events from the owner.
this._listeners = [
navigator.navigationContext.addListener('willfocus', callback),
navigator.navigationContext.addListener('didfocus', callback),
];
}
}
}
componentWillUnmount() {
this._listeners && this._listeners.forEach(listener => listener.remove());
}
}
var 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,
},
});
AppRegistry.registerComponent('PasswordRecovery', () => PasswordRecovery);
I am just trying to get this all setup so that I can display a Google Sign in scene and then navigate from there. The code for that scene so far is here:
GoogSignIn.js
'use strict';
var React = require('react-native');
var { NativeAppEventEmitter } = require('react-native');
var GoogleSignin = require('react-native-google-signin');
var cssVar = require('cssVar');
var { Icon } = require('react-native-icons');
var {
AppRegistry,
StyleSheet,
Text,
View,
TouchableOpacity,
TouchableHighlight,
PixelRatio,
Navigator,
} = React;
var NavigationBarRouteMapper = {
LeftButton: function(route, navigator, index, navState) {
if (index === 0) {
return null;
}
var previousRoute = navState.routeStack[index - 1];
return (
<TouchableOpacity
onPress={() => navigator.pop()}
style={styles.navBarLeftButton}>
<Text style={[styles.navBarText, styles.navBarButtonText]}>
{previousRoute.title}
</Text>
</TouchableOpacity>
);
},
RightButton: function(route, navigator, index, navState) {
return (
null
);
},
Title: function(route, navigator, index, navState) {
return (
<Text style={[styles.navBarText, styles.navBarTitleText]}>
GOOGLE SIGN IN
</Text>
);
},
};
class GoogSignin extends React.Component {
constructor(props) {
super(props);
this.state = {
user: null
};
}
componentWillMount() {
var navigator = this.props.navigator;
var callback = (event) => {
console.log(
`NavigationBarSample : event ${event.type}`,
{
route: JSON.stringify(event.data.route),
target: event.target,
type: event.type,
}
);
};
// Observe focus change events from this component.
this._listeners = [
navigator.navigationContext.addListener('willfocus', callback),
navigator.navigationContext.addListener('didfocus', callback),
];
}
componentWillUnmount() {
this._listeners && this._listeners.forEach(listener => listener.remove());
}
componentDidMount() {
this._configureOauth(
'105558473349-7usegucirv10bruohtogd0qtuul3kkhn.apps.googleusercontent.com'
);
}
renderScene(route, navigator) {
console.log("HERE");
return (
<View style={styles.container}>
<TouchableHighlight onPress={() => {this._signIn(); }}>
<View style={{backgroundColor: '#f44336', flexDirection: 'row'}}>
<View style={{padding: 12, borderWidth: 1/2, borderColor: 'transparent', borderRightColor: 'white'}}>
<Icon
name='ion|social-googleplus'
size={24}
color='white'
style={{width: 24, height: 24}}
/>
</View>
<Text style={{color: 'white', padding: 12, marginTop: 2, fontWeight: 'bold'}}>Sign in with Google</Text>
</View>
</TouchableHighlight>
</View>
);
}
render() {
return (
<Navigator
debugOverlay={false}
style={styles.container}
renderScene={this.renderScene}
navigationBar={
<Navigator.NavigationBar
routeMapper={NavigationBarRouteMapper}
style={styles.navBar}/>
}/>
);
}
_configureOauth(clientId, scopes=[]) {
console.log("WE HERE")
GoogleSignin.configure(clientId, scopes);
NativeAppEventEmitter.addListener('googleSignInError', (error) => {
console.log('ERROR signin in', error);
});
NativeAppEventEmitter.addListener('googleSignIn', (user) => {
console.log(user);
this.setState({user: user});
});
return true;
}
_signIn() {
GoogleSignin.signIn();
}
_signOut() {
GoogleSignin.signOut();
this.setState({user: null});
}
};
var styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
messageText: {
fontSize: 17,
fontWeight: '500',
padding: 15,
marginTop: 50,
marginLeft: 15,
},
button: {
backgroundColor: 'white',
padding: 15,
borderBottomWidth: 1 / PixelRatio.get(),
borderBottomColor: '#CDCDCD',
},
buttonText: {
fontSize: 17,
fontWeight: '500',
},
navBar: {
backgroundColor: 'white',
},
navBarText: {
fontSize: 16,
marginVertical: 10,
},
navBarTitleText: {
color: cssVar('fbui-bluegray-60'),
fontWeight: '500',
marginVertical: 9,
},
navBarLeftButton: {
paddingLeft: 10,
},
navBarRightButton: {
paddingRight: 10,
},
navBarButtonText: {
color: cssVar('fbui-accent-blue'),
},
scene: {
flex: 1,
paddingTop: 20,
backgroundColor: '#EAEAEA',
},
});
module.exports = GoogSignin;
edit: screenshots of inspector:
In your renderScene method, try doing something like this (this will also help you remove that big switch):
Component = route.id
<View style={styles.container}>
<Component navigator={navigator} route={route} />
</View>
styles = StyleSheet.create({
container:
flex: 1
})