I want to import JSON files dynamically based on certain condition. My Code is
import TXT1 from "../Assets/TTCS1.json";
import TXT2 from "../Assets/TTCS2.json";
export class Timetable extends Component {
state = {class: 1};
render() {
return this.state.class === 1 ? (
<View style={styles.container}>
<Text>{TXT1.S5}</Text>
</View>
) : (
<View style={styles.container}>
<Text>{TXT2.S5}</Text>
</View>
);
}
}
These JSON files are large and a particular user will mostly use only any one of the JSON file hence importing all is waste of resources. I found an answer here How can I conditionally import an ES6 module? the answer works fine with JS files, but with JSON files I am confused what is to be put in .then() function.
you can use require.
Created expo snack :
https://snack.expo.io/BJRqgSnqr
import React, { Component } from 'react';
import { Text, View, StyleSheet, ScrollView } from 'react-native';
import * as Constants from 'expo-constants';
var TXT1='',TXT2='';
export default class App extends Component {
state={TXT1:'',TXT2:''}
componentDidMount=()=>
{
TXT1 = require('./assets/TXT1.json');
this.setState({TXT1});
}
render() {
return (
<View style={styles.container}>
<Text>{JSON.stringify(this.state.TXT1)}</Text>
<Text>{JSON.stringify(TXT2)}</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
paddingTop: Constants.statusBarHeight,
backgroundColor: '#ecf0f1',
},
});
Related
I'm doing a weather project on React Native error with PropTypes
The code:
import React from "react";
import PropTypes from 'prop-types';
import { StyleSheet, Text, View } from "react-native";
export default function Wather({temp}) {
return (
<View style={styles.container}>
<Text>{temp}</Text>
</View>
);
}
Wather.propTypes = {
temp:PropTypes.nymber.isRequired,
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "#FDF6AA",
justifyContent: "flex-end",
paddingHorizontal: 30,
paddingVertical: 100,
},
});
Erorr name:
undefined is not an object (evaluating '_propTypes.default.nymber.isRequired')
I think you have made a typo error. It should be PropTypes.number and not PropTypes.nymber
After fixing typo error it should look like this :
Wather.propTypes = { temp:PropTypes.number.isRequired, }
I an using yarn workspaces, and i have 3 packages: app, electron app using react, and shared for all the common stuff. When importing shared in the app or electron, it says that error in vscode:
error
i dont know what to do :/ i tried everything. and the files arent ts, but js.
import { View, StyleSheet, Text } from 'react-native';
import Header from 'shared/components/Header';
//const socket = new Socket("192.168.1.146", 8080, "http");
(async () => {
//await socket.connect();
})();
const styles = StyleSheet.create({
screenContainer: {
flex: 1
},
text: {
fontSize: 20,
color: 'cornflowerblue',
marginTop: 50,
alignSelf: 'center'
}
});
const App = () => {
/*useEffect(() => {
if (socket.getSocket() != undefined && socket.getSocket().connected) {
socket.getSocket().disconnect();
}
});*/
return (
<View styles={styles.screenContainer}>
<Header />
<Text style={styles.text}>I'm a React Native component</Text>
</View>
);
};
export default App;
import React from 'react';
import { View, Text, StyleSheet } from 'react-native';
const styles = StyleSheet.create({
header: {
paddingTop: 50,
backgroundColor: 'red'
},
headerText: {
fontSize: 22,
color: 'white',
fontWeight: 'bold',
paddingHorizontal: 10
}
});
const Header = () => {
return (
<View style={styles.header}>
<Text style={styles.headerText}>I'm a shared component.</Text>
</View>
);
};
export default Header;
create fallback.d.ts with content:
declare module '*';
And include it in your tsconfig.json https://www.typescriptlang.org/tsconfig#include (path to d.ts file relative to tsconfig.json path)
{
"include": ["./fallback.d.ts", ...],
...
}
This will allow you to import from js files.
But imho better would be to convert Header.js file to typescript
so I am really having a hard time with this navigation thing. I am not an expert in Js or react native, but since the person working on this app isn't in the company anymore, I am asked to make some tweaks here and there until a new person comes in but I am struggling with this navigation thing.
so I am using this to go to my two factor identification
any idea what does this navigate do anyway? how can I set it value? do it need to passe it somehow?
full code
import React, {Component} from 'react'
import PropTypes from 'prop-types'
import {
View,
Text,
TouchableHighlight,
Image,
TextInput,
} from 'react-native'
import {requiredFields} from '../helpers/forms'
import BusyButton from '../Common/BusyButton'
import DismissKeyboard from '../Common/DismissKeyboard'
import {Colors} from '../styles'
import LoginStyles from './LogInStyles'
const loginStyles = LoginStyles.createStyles()
/* eslint-disable camelcase,space-before-function-paren */
export default class TwoFactor extends Component {
static propTypes = {
screenProps: PropTypes.object.isRequired,
navigation: PropTypes.object.isRequired,
}
state = {
verificationCode: '',
}
handleSubmit = () => {
try{
const {screenProps: {auth: {sendVerificationCode}}, navigation: {navigate}} = this.props
if (requiredFields(['verificationCode'], ['Verification Code'], this.state)) {
sendVerificationCode(this.state.verificationCode,this.state.user, navigate)
}
return false
}catch(e){
console.log(e)
}
}
render() {
const {screenProps: {auth: {isFetching}}} = this.props
return (
<DismissKeyboard style={loginStyles.pageWrapper}>
<View style={loginStyles.logoContainer}>
<Image
style={loginStyles.logo}
resizeMode="contain"
source={require('../../assets/images/logo-IH_blue_gold-small.png')}
/>
</View>
<View style={loginStyles.containerExpand}>
<Text style={loginStyles.h1}>ID Verification</Text>
<Text style={loginStyles.label}>
A verification code has been sent to the phone number on file. Please enter the code below.
</Text>
<TextInput
style={loginStyles.input}
placeholder="Verification Code"
placeholderTextColor={Colors.lightGray}
onChangeText={(verificationCode) => this.setState({verificationCode})}
keyboardType="number-pad"
/>
</View>
<View style={loginStyles.container}>
<View style={loginStyles.buttonContainer}>
<BusyButton
style={loginStyles.button}
underlayColor={Colors.buttonPrimaryBkgd}
isBusy={isFetching}
onPress={this.handleSubmit}
>
<Text style={loginStyles.buttonText}>Next</Text>
</BusyButton>
</View>
</View>
</DismissKeyboard>
)
}
}
ERROR
it's not spitting any error, but it is not taking me to the next screen.
I want to make an app that makes a compass and compass should changes with changing direction of magnetometer. The code attached below shows a strange error. Although I have run npm install react-timer-mixin to sort the problem.By running this code on Expo it shows an error like
Super expression must either be a null or a function.
import React, {Components} from 'react';
import {Image, ImageBackground, View, Text, StyleSheet} from 'react-native';
import Expo from 'expo';
export default class App extends Components{
state={
isReady: false,
v: null,
};
_setMagnetometerAsync = async() =>{
Expo.Magnetometer.addListener((v)=>{
this.setState({v});
});
}
componentDidMount() {
this._setupMagnetometerAsync();
}
render(){
return(
<View style = {styles.container}>
<Text>{JSON.stringify(this.state.v)}</Text>
<ImageBackground
source = {require('./compassFace.png')}
style = {{
height: 320,
width: 320,
paddingTop:Expo.Constants.statusBarHeight,
alignItems: 'center',
justifyContents: 'center',
}}>
<Image
source = {require('./CompassNeedle.png')}
style={{
height: 420,
width: 420,
opacity: 0.65,
}}
/>
</ImageBackground>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#ecf0f1',
},
paragraph:{
margin: 24,
fontSize: 18,
fontWeight: 'bold',
textAlign: 'center',
color: '#34495e',
},
});
Some fixes:
1.
import React, {Components} from 'react';
to
import * as React from 'react';
2.
componentDidMount(){
this._setupMagnetometerAsync();
}
to
componentDidMount(){
this._setMagnetometerAsync();
}
3.
export default class App extends Components{
to
export default class App extends React.Component{
I'm trying to navigate from Homescreen to another screen(Test).I have 'HomeScreen.js' below. Once I click on the register button, I get the above mentioned error.
I've been at this for a whole day, but can't seem to get a straight forward answer.
The error is on my 'Homescreen.js' (Attached screenshot error)
Screenshot
Error is pointing to: this.props.navigator.push under the _handleRegisterView function.
HomeScreen.js
import React from 'react';
import {
StyleSheet,
Text,
View,
AsyncStorage,
Component,
TouchableHighlight,
AppRegistry
} from 'react-native';
import Test from './Test';
import { StackNavigator } from 'react-navigation';
class HomeScreen extends React.Component {
static navigationOptions = {
title: 'SpeedHack',
};
_handleRegisterView = () => {
this.props.navigator.push({
title: 'Test',
component: Test,
backButtonTitle: 'Back'
})
//alert('Register button Pressed!.');
}
render() {
return (
<View style={styles.container}>
<TouchableHighlight onPress={this._handleRegisterView}>
<Text style={[styles.button, styles.blueButton]}>
Register
</Text></View>
);
}
}
Test.js (Doesn't really do anything interesting, loads an image)
import React from 'react';
import { Component, StyleSheet, Text, View, Image } from 'react-native';
class Test extends React.Component {
render() {
let pic = {
uri: 'https://upload.wikimedia.org/wikipedia/commons/d/de/Bananavarieties.jpg'
};
return (
<View style={styles.container}>
<Text>Ssup Dude! Want some bananas?</Text>
<Image source = {pic} style = {{width: 300, height: 300}}/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
You seem to be confused. In react-navigation in order to push a screen, you do not do this.props.navigator.push, you use this.props.navigation.navigate.