Unable to find the react native variable "ConnectionStatus" - javascript

I am trying to implement a code that tests the internet connectivity using react native NetInfo from '#react-native-community/netinfo'. It is giving me an error that says "Can't find variable: connectionStatus". I tried my best declare properly but for some reason it is giving the error above.
import React, { Component } from 'react'
import NetInfo from '#react-native-community/netinfo';
import { ActivityIndicator, StyleSheet,View, Text } from 'react-native'
import { WebView } from 'react-native-webview';
export default class BrowserScreen extends Component {
constructor(props) {
super(props);
this.state = {
connectionStatus: false,
}
}
componentDidMount() {
const {navigation} = this.props;
this.focusListener = navigation.addListener('didFocus', () => {
this.checkConnected();
})
}
async checkConnected() {
const networkState = await NetInfo.fetch();
if (networkState.isConnected) {
this.setState({ connectionStatus: true });
}
}
LoadingIndicatorView() {
return <ActivityIndicator
color='#009b88'
size='large'
style={styles.ActivityIndicatorStyle}
/>
}
render() {
let url = this.props.navigation.getParam('webUrl');
console.log(url) ;
return (
/**
* use the webview here to display the webpage
*/
connectionStatus ? (
<WebView
source={{ uri: url }}
renderLoading={this.LoadingIndicatorView}
startInLoadingState={true}
/>
) :
(
<View>
<Text> No Connection !!!!</Text>
</View>)
)
}
}
const styles = StyleSheet.create({
ActivityIndicatorStyle: {
flex: 1,
justifyContent: 'center'
}
})

connectionStatus is stored in state, refer to it as this.state.connectionStatus

Related

how to pass data to another screen in react native (and how to receive it)?

i want to pass data from this screen (Lihat.js)
import React, { Component } from 'react';
import { View, Text } from 'react-native';
import { style } from './Style';
class Lihat extends Component {
constructor(props) {
super(props);
this.state = {
nama:'',
nim:'',
prodi:'',
no_telp:'',
alamat:'',
listData:[],
};
this.url = "http://192.168.100.161/mhs/mhs.php"
// this.url = "http://192.168.162.248/mhs/mhs.php"
}
componentDidMount(){
this.ambilListData()
}
async ambilListData(){
await fetch(this.url)
.then((response)=>response.json())
.then((json)=>{
console.log("hasil :"+JSON.stringify(json.data.result))
this.setState({listData:json.data.result})
})
.catch((error)=>{
console.log(error);
})
}
async klikDelete(id){
await fetch(this.url+"/?op=delete&id="+id)
.then((response)=>response.json())
.then((json)=>{
alert('Data berhasil didelete');
this.ambilListData();
})
.catch((error)=>{
console.log(error)
})
}
render() {
return (
<View style={style.lihatWrapper}>
<View style={style.viewData}>
{
this.state.listData.map((val,index)=>(
<View style={style.viewList} key={index}>
<Text style={style.textListNama}>Nama :{val.nama}</Text>
<View style={{flexDirection:'column'}}>
{/* i want to pass data from this button / link */}
<Text style={style.textListLihat} onPress={()=>this.props.navigation.navigate('Detail',{id:this.state.listData.map()})}>Detail</Text>
<Text style={style.textListEdit} onPress={()=>this.props.navigation.navigate('Update')}>Edit</Text>
<Text style={style.textListDelete} onPress={()=>this.klikDelete(val.id)}>Delete</Text>
</View>
</View>
))
}
</View>
</View>
);
}
}
export default Lihat;
to this screen (Detail.js)
import { TabRouter, validatePathConfig } from '#react-navigation/native';
import React, { Component } from 'react';
import { View, Text, FlatList, SafeAreaView} from 'react-native';
import { style } from './Style';
import Lihat from './Lihat';
class Detail extends Component {
route
constructor(props) {
super(props);
this.state = {
nama:'',
nim:'',
prodi:'',
no_telp:'',
alamat:'',
listData:[]
};
this.url = "https://192.168.100.161/mhs/mhs.php"
// this.url = "http://192.168.162.248/mhs/mhs.php"
}
componentDidMount(){
this.ambilListData()
}
async ambilListData(){
await fetch(this.url)
.then((response)=>response.json())
.then((json)=>{
console.log("hasil: "+json.data.result)
this.setState({listData:json.data.result})
})
.catch((error)=>{
console.log(error);
})
}
render() {
return (
<View style={style.viewWrapper}>
<Text style={style.content}>
{
this.state.listData.map((val,index)=>(
<View style={style.viewList} key={index}>
<Text style={style.textListNama}></Text>
<Text style={style.textListNama}></Text>
</View>
))
}
</Text>
</View>
);
}
}
export default Detail;
so when i press 'detail', the screen will navigate to detail.js and display the data detail.
Lihat.js
enter image description here
Thanks
i already read react native passing data tutorial. but i cant understand it. and when i search on youtube mostly the tutorial is using axios.
move the data to the parent component and handle it and from there,
from there you can access that data in both the components
lifting the state up
You can try this way:
<Text style={style.textListLihat} onPress={()=>this.props.navigation.navigate('Detail',{listData: this.state.listData})}>Detail</Text>
and setting the value passed in the state of Detail:
this.state = {
nama: '',
nim: '',
prodi: '',
no_telp: '',
alamat: '',
listData: this.props.route.params.listData || [],
};

Rendering DB entry in Expo

This is my first go at a expo/react native app, and i have struck trouble,
I am able to console.log my firestore db entries fine, but i cant seem to work out how to render them to a view, and to make location cards like the attached image, 1
Can anyone help?
import React, { Component } from "react";
import { View, Text, StyleSheet } from "react-native";
import firebase from "firebase";
require("firebase/firestore");
const config = {
};
if (!firebase.apps.length) {
firebase.initializeApp(config);
}
var db = firebase.firestore();
class componentName extends Component {
componentDidMount() {
db.collection("event")
.get()
.then((snapshot) => {
snapshot.docs.forEach((doc) => {
console.log(doc.data());
});
});
}
render() {
return (
<View style={styles.container}>
<Text>d</Text>
</View>
);
}
}
export default componentName;
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: "center",
justifyContent: "center",
},
});
For this you need to create a state and need to include your db entries in state, some thing like this:
constructor(props){
super(props);
this.state={
data:[]
}
}
And set your db entries like this in state data:
componentDidMount() {
db.collection("event")
.get()
.then((snapshot) => {
this.setState({
data : snapshot.docs
})
}
And in view you can render it like this:
return (
<View style={styles.container}>
{
this.state.data.map((item,key) =>{
return(
<Text>{item.campusName}</Text>
<Text>{item.campusAddress}</Text>
<Text>{item.campusTimings}</Text>
)
})
}
</View>
);
Hope this helps!

Animate static SVG file with react-native-svg

I'm struggling to get react-native-svg animate in React Native. I also tried the method they suggest with react-native-svg-transformation but it didn't suit my case since I'm working with many files and render them dynamically.
Here's my render file:
import React from "react";
import { View, Text } from "react-native";
import { SvgXml } from "react-native-svg";
import SvgAssets from "../resources/SvgAssets";
import AssetsHelper from "../common/AssetsHelper";
class ChineseCharacter extends React.Component {
constructor(props) {
super(props);
this.state = {
xmlData: "",
};
}
render() {
const { xmlData, file } = this.state;
if (xmlData.length === 0) {
return <View />;
}
return (
<View style={{ flex: 1 }}>
<SvgXml xml={xmlData} width="200" height="200" />
</View>
);
}
componentDidMount(): void {
const { character } = this.props;
const characterUnicode = character.charCodeAt(0);
const file = SvgAssets[characterUnicode.toString()];
AssetsHelper(file)
.then(result => {
this.setState({
xmlData: result,
});
})
.catch(err => console.log(err));
}
}
export default ChineseCharacter;
AssetsHelper is basically reading the svg file and convert them to string in order to pass to SvgXml.
SvgAssets is an object with key as the charCode and value is the file, something like this:
const assets = {
"11904": require("./svgs/11904.svg"),
...
}
Thank in advance.
After few struggling hours, I have found a work around for this problem. I don't use react-native-svg anymore, instead I parse the .svg file to string and put it in react-native-webview. Work like a charm!
render() {
// #ts-ignore
const { xmlData, file } = this.state;
if (xmlData.length === 0) {
return <View />;
}
return (
<View style={{ width: 300, height: 300 }}>
<WebView
source={{ html: xmlData }}
style={{ backgroundColor: "transparent", width: 300, height: 300 }}
/>
</View>
);
}
Try to import the svg files inside ChineseCharacter class.
import svgXml11904 from './svgs/11904.svg'
const assets = {
"11904": svgXml11904,
...
}

React-Native - RangeError appears when trying to inject splash screen image

I'm trying to inject a splash screen image on to my app but I keep getting error message: RangeError: Maximum call stack size exceeded Project is react-native-cli, could that be the issue?
import React, { Component } from 'react';
import { Image, View } from 'react-native';
import { inject } from 'mobx-react';
#inject("stores")
export default class SplashScreen extends Component {
constructor(props) {
super(props)
}
componentDidMount() {
const { stores, navigation } = this.props;
setTimeout (() => {
navigation.navigate("Login")
}, stores.config.SplashTime)
}
render() {
const { stores } = this.props
return (
<View style={{flex: 1}}>
<Image style={{flex: 1, width: null, height: null}} source={stores.config.SplashIMG}/>
</View>
)
}
}
Changed img link to require and amended component to DidUpdate.
componentDidUpdate() {
const { stores, navigation } = this.props;
console.log(this.props)
setTimeout (() => {
navigation.navigate("Login")
}, stores.config.SplashTime)
}
render() {
const { stores } = this.props
return (
<View style={{flex: 1}}>
<Image style={{flex: 1, width: null, height: null}} source={require('../../images/splash.jpg')}/>
</View>)
}
}```

React Native NetInfo 'connectionChange' event not fired

I have two PoCs I'm working on. 1)RNRestAPI. 2)RNNavigate.
In RNRestAPI index.android.js and index.ios.js both looks like this;
import React, { Component } from 'react';
import {
AppRegistry,
View
} from 'react-native';
import Login from './app/screens/Login/Login';
import About from './app/screens/About/About';
export default class RNRestAPI extends Component {
render() {
return (
<View style={{flex:1}}>
<Login />
</View>
);
}
}
AppRegistry.registerComponent('RNRestAPI', () => RNRestAPI);
Login.js is like this;
import React, { Component } from 'react';
import {
AppRegistry,
View,
TextInput,
StyleSheet,
Button,
Text,
Alert,
TouchableHighlight,
Platform,
Image,
NetInfo,
ProgressBarAndroid,
ProgressViewIOS
} from 'react-native';
import I18n from '../../resources/strings/i18n';
import Colors from '../../resources/styles/colors';
import Dimensions from '../../resources/styles/dimensions';
import Styles from '../../resources/styles/styles';
import Config from '../../config';
export default class Login extends Component {
constructor() {
super();
this.state = {
username:'',
password:'',
buttonLoginDisabled:false,
isConnected:false
}
// I18n.locale = 'en';
}
componentWillMount() {
NetInfo.addEventListener(
'connectionChange',
this.handleConnectivityChange.bind(this)
);
}
componentWillUnmount() {
NetInfo.removeEventListener('connectionChange', handleConnectivityChange);
}
handleConnectivityChange(connectionInfo) {
console.log('First change, type: ' + connectionInfo.type + ', effectiveType: ' + connectionInfo.effectiveType);
if(connectionInfo.type === 'none') {
this.setState({
isConnected:false,
buttonLoginDisabled:true
});
} else {
this.setState({
isConnected:true,
buttonLoginDisabled:false
});
}
}
onLoginClicked() {
var valid = this.validateLoginForm();
if(valid === true) {
this.setState({
buttonLoginDisabled:true
});
this.makeLoginRequest();
} else {
Alert.alert(I18n.t('dialogLoginInvalidTitle'), I18n.t('dialogLoginInvalidMessage'));
}
}
validateLoginForm() {
if(this.state.username === '') {
return false;
}
if(this.state.password === '') {
return false;
}
return true;
}
makeLoginRequest() {
fetch('http://webapitest', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'MobilePlatformId': Config.MobilePlatformId,
'ApplicationId': Config.ApplicationId,
'Version': '1.9.6'
},
body: JSON.stringify({
Username: this.state.username,
Password: this.state.password
})
})
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson);
if(responseJson.Token !== null) {
console.log('login successful');
} else {
this.setState({
buttonLoginDisabled:false
});
Alert.alert(I18n.t('dialogInvalidLoginTitle'), I18n.t('dialogInvalidLoginMesage'));
}
})
.catch((error) => {
console.log(eror);
this.setState({
buttonLoginDisabled:false
});
})
}
setUsername(value) {
this.setState({
username:value
});
}
setPassword(value) {
this.setState({
password:value
});
}
onMoreClicked() {
Alert.alert(I18n.t('dialogLearnMoreTitle'), I18n.t('dialogLearnMoreMesage'));
}
getLoginButtonStyle() {
if(this.state.buttonLoginDisabled) {
return styles.buttonLoginDisabled;
} else {
return styles.buttonLogin;
}
}
render() {
return (
<View style={styles.container}>
<View>
<Image source={require('../../resources/images/facilit_logo_welcome.png')}
style={{width:266, height:50, resizeMode:Image.resizeMode.cover}} />
</View>
<View style={styles.wrapperLoginInput}>
<TextInput
keyboardType='default'
placeholder={I18n.t('username')}
returnKeyType='next'
onChangeText={(value) => this.setUsername(value)}
style={Styles.primaryTextInput} />
<TextInput secureTextEntry={true}
placeholder={I18n.t('password')}
onChangeText={(value) => this.setPassword(value)}
style={Styles.primaryTextInput} />
<TouchableHighlight onPress={this.onLoginClicked.bind(this)}
style={{marginTop:(Platform.OS === 'ios') ? 10 : 30}}
underlayColor='#00000000'
disabled={this.state.buttonLoginDisabled}>
<View style={this.getLoginButtonStyle()}>
<Text style={styles.buttonLoginText}>{I18n.t('login')}</Text>
</View>
</TouchableHighlight>
<View style={styles.wrapperLearnMoreLink}>
<TouchableHighlight onPress={this.onMoreClicked.bind(this)}
underlayColor='#00000000'>
<Text style={styles.learnMoreLink}>{I18n.t('learnMore')}</Text>
</TouchableHighlight>
</View>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex:1,
backgroundColor:Colors.primaryBlue,
justifyContent:'center',
alignItems:'center'
},
wrapperLoginInput: {
width:300,
marginTop:100
},
buttonLogin: {
backgroundColor:Colors.primaryYellow,
alignItems:'center',
height:Dimensions.primaryButtonHeight,
justifyContent:'center',
borderRadius:Dimensions.primaryButtonBorderRadius,
borderWidth:Dimensions.primaryButtonBorderWidth,
borderColor:Colors.primaryButtonBorderColor,
},
buttonLoginDisabled: {
backgroundColor:Colors.primaryButtonDisabledGray,
alignItems:'center',
height:Dimensions.primaryButtonHeight,
justifyContent:'center',
borderRadius:Dimensions.primaryButtonBorderRadius,
borderWidth:Dimensions.primaryButtonBorderWidth,
borderColor:Dimensions.primaryButtonBorderColor,
},
buttonLoginText: {
fontSize:Dimensions.primaryButtonFontSize,
color:Colors.primaryButtonFontColor
},
wrapperLearnMoreLink: {
alignItems:'center',
marginTop:150,
},
learnMoreLink: {
color:Colors.secondaryTextColor,
textDecorationLine:'underline'
}
});
AppRegistry.registerComponent('Login', () => Login);
The important bits are componentWillMount() and handleConnectivityChange(connectionInfo). They work as expected and my code handles online/offline scenarios.
The second PoC(RNNavigate) is basically a copy of RNRestAPI but with the inclusion of react-navigation https://reactnavigation.org/. I'm basically trying to create the navigation for my app after the user logs in successfully into my app. So accordingly I have done the following modification to my code.
1) Create App.js
import React, { Component } from 'react';
import {
AppRegistry,
View
} from 'react-native';
import Login from './app/screens/Login/Login';
import About from './app/screens/About/About';
import FacilitySearch from './app/screens/FacilitySearch/FacilitySearch';
import { StackNavigator } from 'react-navigation';
export default class RNNavigate extends Component {
render() {
return (
<View style={{flex : 1}}>
<RNNavigateApp />
</View>
);
}
}
const RNNavigateApp = StackNavigator({
Login : {
screen : Login,
navigationOptions : ({navigation}) => ({
header : null
})
},
About : { screen : About },
FacilitySearch : {
screen : FacilitySearch,
navigationOptions : ({
headerLeft : null
})
}
});
AppRegistry.registerComponent('RNNavigate', () => RNNavigate);
2) Modify index.android.js and index.ios.js to;
import './App.js';
Login.js is untouched. But the connectionChange event is no longer fired. Any expert help is much appreciated to guide me figuring out as to why it's no longer fired or educate me on if I have done something wrong in terms of using React Navigate.
For me, the event was not fired because I didn't restart my react-native server after adding <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> in the AndroidManifest.xml.
Kill your server and restart it after then it should fire.

Categories

Resources