Component Exception - Can't find variable: direction - react-native

I am trying to run this app in react but it keeps giving me that error that it cannot find the variable direction. How do I solve this. The Code is below.
APP.js
// Importing Libs
import React, {useState} from 'react';
import { StyleSheet, View , SafeAreaView} from 'react-native';
import Header from './APP/Components/Header';
import StartGameScreen from './APP/Screens/StartGameScreen';
import GameScreen from './APP/Screens/GameScreen';
export default function App() {
const [userNumber, setUserNumber] = useState();
const startGameHandler = (selectedNumber) => {
setUserNumber(selectedNumber);
};
let content = <StartGameScreen onStartGame={startGameHandler} />;
if (userNumber) {
content = <GameScreen userChoice={userNumber} />;
}
return (
<View style={styles.screen}>
<Header title="GUESS THE NUMBER" />
{content}
</View>
);
}
const styles = StyleSheet.create({
screen: {
flex: 1
},
});
GameScreen.js
import React, {useState, useRef} from 'react';
import {View , Text , StyleSheet, Button, Alert} from 'react-native';
const generateRandomBetween = (min, max , exclude) => {
min = Math.ceil(min);
max = Math.floor(max);
const rndNum = Math.floor(Math.random() * (max - min)) + min;
if (rndNum === exclude) {
return generateRandomBetween(min, max, exclude);
} else {
return rndNum;
}
};
const GameScreen = props => {
const [currentGuess, setCurrentGuess] = useState(generateRandomBetween(1, 99, props.userChoice));
const currentLow = useRef(1);
const currentHigh = useRef(99);
const nextGuessHandler = direction => {
if ((direction === 'lower' && currentGuess < props.userChoice) || (direction === 'greater' && currentGuess > props.userChoice) ) {
Alert.alert('Don\'t lie to me', 'You Can\'t Trick Me' [{text: 'I won\'t lie again , SORRY!', style: 'cancel'}]);
}
}
if ( direction === 'lower') {
currentHigh.current = currentGuess;
} else {
currentLow.current = currentGuess;
}
const nextNumber = generateRandomBetween(currentLow.current, currentHigh.current, currentGuess);
currentGuess(nextNumber);
return (
<View style={styles.screen}>
<Text>Opponent Guess</Text>
<View style={styles.guessNumberContainer}>
<Text style={styles.guessText}>{currentGuess}</Text>
</View>
<View style={styles.buttonContainer}>
<Button title="LOWER" onPress={nextGuessHandler.bind(this, 'lower')} />
<Button title="HIGHER" onPress={nextGuessHandler.bind(this, 'greater')} />
</View>
</View>
)
};
const styles = StyleSheet.create({
gameScreenContainer: {
width: 300,
maxWidth: '80%',
alignItems: 'center',
shadowColor: 'black',
shadowOffset: { width: 0, height: 2},
shadowRadius: 4,
shadowOpacity: 0.26,
backgroundColor:'#fff',
elevation: 8 ,
padding: 20,
borderRadius: 15,
marginTop: 30
},
guessNumberContainer:{
borderWidth: 2,
borderColor: "#FFC45D",
padding: 10,
borderRadius: 10,
marginVertical: 10,
alignItems: 'center',
justifyContent:'center',
width: 200
},
guessText:{
color: "#FFC45D",
fontSize: 22
},
screen:{
flex: 1,
padding: 10,
alignItems: 'center'
},
buttonContainer:{
width: 300,
maxWidth: '80%',
justifyContent: 'space-between',
alignItems: 'center',
shadowColor: 'black',
shadowOffset: { width: 0, height: 2},
shadowRadius: 4,
shadowOpacity: 0.26,
backgroundColor:'#fff',
elevation: 8 ,
padding: 20,
borderRadius: 15,
flexDirection: 'row',
marginTop: 20
}
});
export default GameScreen;
I have no idea how to fix this , dont even know where to start from. I have tried changing the direction name to something else but still gives an error and i made sure React was imported , i have no idea what i am missing.

Based on the conversation in the comments I assume you want something like this...
const nextGuessHandler = direction => {
if ((direction === 'lower' && currentGuess < props.userChoice) || (direction === 'greater' && currentGuess > props.userChoice) ) {
Alert.alert('Don\'t lie to me', 'You Can\'t Trick Me' [{text: 'I won\'t lie again , SORRY!', style: 'cancel'}]);
}
if ( direction === 'lower') {
currentHigh.current = currentGuess;
} else {
currentLow.current = currentGuess;
}
}
const nextNumber...

Related

"Can't perform a React state update on an unmounted component" Follow by continuous "TYPE ERORR: null is not an object"

The app I'm working on is a multi-game app (a bird game, mole game, and minesweeper). The start screen is the menu. It gives me a cycle warning on this screen. When I tap to start the mole game, it plays naturally, but the moment I press the back button to go back to the menu, I receive errors: "Can't perform a React state update on an unmounted component" error follow by continuous "TYPE ERORR: null is not an object".
Screenshots:
Cycle warning
Null is not an object
Node.js errors
Mole Game's App.js
import {
View,
StyleSheet,
Image,
SafeAreaView,
Text,
TouchableWithoutFeedback
} from 'react-native';
import Images from './assets/Images';
import Constants from './Constants';
import Mole from './Mole';
import GameOver from './GameOver';
import Clear from './Clear';
import Pause from './Pause';
const DEFAULT_TIME = 20;
const DEFAULT_STATE = {
level: 1,
score: 0,
time: DEFAULT_TIME,
cleared: false,
paused: false,
gameover: false,
health: 100
}
export default class MoleGame extends Component {
constructor(props) {
super(props);
this.moles = [];
this.state = DEFAULT_STATE;
this.molesPopping = 0;
this.interval = null;
this.timeInterval = null;
}
componentDidMount = () => {
this.setupTicks(DEFAULT_STATE, this.pause);
}
setupTicks = () => {
let speed = 750 - (this.state.level * 50);
if (speed < 350) {
speed = 350;
}
this.interval = setInterval(this.popRandomMole, speed);
this.timeInterval = setInterval(this.timerTick, 1000);
}
reset = () => {
this.molesPopping = 0;
this.setState(DEFAULT_STATE, this.setupTicks)
}
pause = () => {
if (this.interval) clearInterval(this.interval);
if (this.timeInterval) clearInterval(this.timeInterval);
this.setState({
paused: true
});
}
resume = () => {
this.molesPopping = 0;
this.setState({
paused: false
}, this.setupTicks);
}
nextLevel = () => {
this.molesPopping = 0;
this.setState({
level: this.state.level + 1,
cleared: false,
gameover: false,
time: DEFAULT_TIME
}, this.setupTicks)
}
timerTick = () => {
if (this.state.time === 0) {
clearInterval(this.interval);
clearInterval(this.timeInterval);
this.setState({
cleared: true
})
} else {
this.setState({
time: this.state.time - 1
})
}
}
gameOver = () => {
clearInterval(this.interval);
clearInterval(this.timerInterval);
this.setState({
gameover: true
})
}
onDamage = () => {
if (this.state.cleared || this.state.gameOver || this.state.paused) {
return;
}
let targetHealth = this.state.health - 10 < 0 ? 0 : this.state.health - 20;
this.setState({
health: targetHealth
});
if (targetHealth <= 0) {
this.gameOver();
}
}
onHeal = () => {
let targetHealth = this.state.health + 10 > 100 ? 100 : this.state.health + 10
this.setState({
health: targetHealth
})
}
onScore = () => {
this.setState({
score: this.state.score + 1
})
}
randomBetween = (min, max) => {
return Math.floor(Math.random() * (max - min + 1) + min);
}
onFinishPopping = (index) => {
this.molesPopping -= 1;
}
popRandomMole = () => {
if (this.moles.length != 12) {
return;
}
let randomIndex = this.randomBetween(0, 11);
if (!this.moles[randomIndex].isPopping && this.molesPopping < 3) {
this.molesPopping += 1;
this.moles[randomIndex].pop();
}
}
render() {
let healthBarWidth = (Constants.MAX_WIDTH - Constants.XR * 100 - Constants.XR * 60 - Constants.XR * 6) * this.state.health / 100;
return (
<View style={styles.container}>
<Image style={styles.backgroundImage} resizeMode="stretch" source={Images.background} />
<View style={styles.topPanel}>
<SafeAreaView>
<View style={styles.statsContainer}>
<View style={styles.stats}>
<View style={styles.levelContainer}>
<Text style={styles.levelTitle}>Level</Text>
<Text style={styles.levelNumber}>{this.state.level}</Text>
</View>
</View>
<View style={styles.stats}>
<View style={styles.timeBar}>
<Text style={styles.timeNumber}>{this.state.time}</Text>
</View>
<Image style={styles.timeIcon} resizeMode="stretch" source={Images.timeIcon} />
</View>
<View style={styles.stats}>
<View style={styles.scoreBar}>
<Text style={styles.scoreNumber}>{this.state.score}</Text>
</View>
<Image style={styles.scoreIcon} resizeMode="stretch" source={Images.scoreIcon} />
</View>
<View style={styles.stats}>
<TouchableWithoutFeedback onPress={this.pause}>
<View style={styles.pauseButton}>
<Image style={styles.pauseButtonIcon} resizeMode="stretch" source={Images.pauseIcon} />
</View>
</TouchableWithoutFeedback>
</View>
</View>
<View style={styles.healthBarContainer}>
<View style={styles.healthBar}>
<View style={[styles.healthBarInner, { width: healthBarWidth }]} />
</View>
<Image style={styles.healthIcon} resizeMode="stretch" source={Images.healthIcon} />
</View>
</SafeAreaView>
</View>
<View style={styles.playArea}>
{Array.apply(null, Array(4)).map((el, rowIdx) => {
return (
<View style={styles.playRow} key={rowIdx}>
{Array.apply(null, Array(3)).map((el, colIdx) => {
let moleIdx = (rowIdx * 3) + colIdx;
return (
<View style={styles.playCell} key={colIdx}>
<Mole
index={moleIdx}
onDamage={this.onDamage}
onHeal={this.onHeal}
onFinishPopping={this.onFinishPopping}
onScore={this.onScore}
ref={(ref) => { this.moles[moleIdx] = ref }}
/>
</View>
)
})}
</View>
)
})}
</View>
{this.state.cleared && <Clear onReset={this.reset} onNextLevel={this.nextLevel} level={this.state.level} score={this.state.score} />}
{this.state.gameover && <GameOver onReset={this.reset} level={this.state.level} score={this.state.score} />}
{this.state.paused && <Pause onReset={this.reset} onResume={this.resume} />}
</View>
)
}
};
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'column'
},
backgroundImage: {
width: Constants.MAX_WIDTH,
height: Constants.MAX_HEIGHT,
position: 'absolute'
},
topPanel: {
position: 'absolute',
top: 0,
left: 0,
right: 0,
height: Constants.YR * 250,
flexDirection: 'column'
},
statsContainer: {
width: Constants.MAX_WIDTH,
height: Constants.YR * 120,
flexDirection: 'row'
},
stats: {
flex: 1,
justifyContent: 'center',
alignItems: 'center'
},
pauseButton: {
width: Constants.YR * 50,
height: Constants.YR * 50,
backgroundColor: 'black',
borderColor: 'white',
borderWidth: 3,
borderRadius: 10,
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center'
},
pauseButtonIcon: {
width: Constants.YR * 25,
height: Constants.YR * 25,
},
levelContainer: {
width: Constants.YR * 80,
height: Constants.YR * 80,
backgroundColor: '#ff1a1a',
borderColor: 'white',
borderWidth: 3,
borderRadius: 10,
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center'
},
levelTitle: {
fontSize: 21,
color: 'white',
fontFamily: 'LilitaOne'
},
levelNumber: {
fontSize: 17,
color: 'white',
fontFamily: 'LilitaOne'
},
scoreIcon: {
position: 'absolute',
left: 0,
width: Constants.YR * 40,
height: Constants.YR * 40,
},
scoreBar: {
height: Constants.YR * 25,
position: 'absolute',
left: 20,
right: 5,
backgroundColor: 'white',
borderRadius: 13,
justifyContent: 'center',
alignItems: 'center'
},
scoreNumber: {
fontSize: 17,
color: 'black',
fontFamily: 'LilitaOne',
},
timeIcon: {
position: 'absolute',
left: 0,
width: Constants.YR * 40,
height: Constants.YR * 40,
},
timeBar: {
height: Constants.YR * 25,
position: 'absolute',
left: 20,
right: 5,
backgroundColor: 'white',
borderRadius: 13,
justifyContent: 'center',
alignItems: 'center'
},
timeNumber: {
fontSize: 17,
color: 'black',
fontFamily: 'LilitaOne',
},
healthBarContainer: {
height: Constants.YR * 40,
width: Constants.MAX_WIDTH - Constants.XR * 120,
marginLeft: Constants.XR * 60
},
healthIcon: {
position: 'absolute',
top: 0,
left: 0,
width: Constants.YR * 46,
height: Constants.YR * 40,
},
healthBar: {
height: Constants.YR * 20,
width: Constants.MAX_WIDTH - Constants.XR * 100 - Constants.XR * 60,
marginLeft: Constants.XR * 40,
marginTop: Constants.YR * 10,
backgroundColor: 'white',
borderRadius: Constants.YR * 10
},
healthBarInner: {
position: 'absolute',
backgroundColor: '#ff1a1a',
left: Constants.XR * 3,
top: Constants.YR * 3,
bottom: Constants.YR * 3,
borderRadius: Constants.YR * 8
},
playArea: {
width: Constants.MAX_WIDTH,
marginTop: Constants.YR * 250,
height: Constants.MAX_HEIGHT - Constants.YR * 250 - Constants.YR * 112,
flexDirection: 'column',
},
playRow: {
height: (Constants.MAX_HEIGHT - Constants.YR * 250 - Constants.YR * 112) / 4,
width: Constants.MAX_WIDTH,
flexDirection: 'row',
},
playCell: {
width: Constants.MAX_WIDTH / 3,
height: (Constants.MAX_HEIGHT - Constants.YR * 250 - Constants.YR * 112) / 4,
alignItems: 'center'
}
});
Mole.js
import { View, StyleSheet, Button, Image, TouchableWithoutFeedback } from 'react-native';
import Images from './assets/Images';
import SpriteSheet from 'rn-sprite-sheet';
//import Constants from './Constants';
export default class Mole extends Component {
constructor (props) {
super(props);
this.mole = null;
this.actionTimeout = null;
this.isPopping = false;
this.isWacked = false;
this.isHealing = false;
this.isAttacking = false;
this.isFeisty = false;
}
pop =()=>{
this.isWacked = false;
this.isPopping = true;
this.isAttacking = false;
this.isFeisty = Math.random() < 0.4;
if(!this.isFeisty){
this.isHealing = Math.random() < 0.12;
}
if(this.isHealing){
this.mole.play({
type: "heal",
onFinish : ()=>{
this.actionTimeout = setTimeout(()=>{
this.mole.play({
type : "hide",
fps: 24,
onFinish: ()=>{
this.isPopping = false;
this.props.onFinishPopping(this.props.index);
}
})
}, 1000);
}
})
}
else{
this.mole.play({
type : "appear",
fps: 24,
onFinish: ()=>{
if (this.isFeisty){
this.actionTimeout = setTimeout(() => {
this.isAttacking = true;
this.props.onDamage();
this.mole.play({
type: "attack",
fps: 12,
onFinish: () => {
this.mole.play({
type: "hide",
fps: 24,
onFinish: () => {
this.isPopping = false;
this.props.onFinishPopping(this.props.index);
}
})
}
})
}, 1000)
}
else{
this.actionTimeout = setTimeout(()=>{
this.mole.play({
type : "hide",
fps: 24,
onFinish: ()=>{
this.isPopping = false;
this.props.onFinishPopping(this.props.index);
}
})
}, 1000);
}
}
})
}
}
whack = ()=>{
if(!this.isPopping || this.isWacked || this.isAttacking){
return;
}
if (this.actionTimeout){
clearTimeout(this.actionTimeout);
}
this.isWacked = true;
this.props.onScore ();
if( this.isHealing){
this.props.onHeal();
}
this.mole.play({
type: "dizzy",
fps: 24,
onFinish: () => {
this.mole.play({
type: "faint",
fps: 24,
onFinish: () => {
this.isPopping = false;
this.props.onFinishPopping(this.props.index);
}
})
}
})
}
render() {
return (
<View style= {styles.container}>
<SpriteSheet
ref= {ref=> {this.mole = ref}}
source = {Images.sprites}
columns = {6}
rows = {8}
width = {100}
animations = {{
idle: [0],
appear: [1,2,3,4],
hide: [4,3,2,1,0],
dizzy : [36,37,38],
faint: [42,43,44,0],
attack: [11,12,13,14,15,16],
heal: [24,25,26,27,28,29,30,31,32,33]
}} />
<TouchableWithoutFeedback onPress= {this.whack} style= {{position: 'absolute', top: 0 , bottom:0, left:0, right:0 }}>
<View style= {{position: 'absolute', top: 0 , bottom:0, left:0, right:0 }} />
</TouchableWithoutFeedback>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1
}
})
index.js (Navigation)
import React from "react";
import { NavigationContainer } from '#react-navigation/native';
import { createStackNavigator } from '#react-navigation/stack';
import MoleGame from './Game1/App.js'
import BirdGame from './Game2/App.js'
import HomeScreen from './Game3/screens/HomeScreen.js'
import GameScreen from './Game3/screens/GameScreen.js'
import Home from './Home.js'
const Stack = createStackNavigator();
export default App = () => {
return (
<NavigationContainer>
<Stack.Navigator screenOptions={{ headerShown: false, gestureEnabled: false, }} >
<Stack.Screen name="Home" component={Home} />
<Stack.Screen name="MoleGame" component={MoleGame} />
<Stack.Screen name="BirdGame" component={BirdGame} />
<Stack.Screen name="MineSweeperHome" component={HomeScreen} />
<Stack.Screen name="MineSweeperGame" component={GameScreen} />
</Stack.Navigator>
</NavigationContainer>
);
};
Home.js
import { View, Text, TouchableOpacity, Dimensions, StyleSheet } from 'react-native';
const GameButton = ({ label, onPress, style }) => {
return (
<TouchableOpacity
style={style}
onPress={onPress}
>
<Text style={styles.text}>{label}</Text>
</TouchableOpacity>
);
};
export default Home = ({ navigation }) => {
return (
<View style={styles.container}>
<View style={styles.welcome}>
<Text style={styles.text}> Welcome! </Text>
</View>
<View style={styles.buttonContainer}>
<GameButton
label={'Play Bird Game'}
onPress={() => navigation.navigate('BirdGame')}
style={styles.gameButton}
/>
<GameButton
label={'Play Mole Game'}
onPress={() => navigation.navigate('MoleGame')}
style={{ ...styles.gameButton, backgroundColor: 'green' }}
/>
<GameButton
label={'Play MineSweeper Game'}
onPress={() => navigation.navigate('MineSweeperHome')}
style={{ ...styles.gameButton, backgroundColor: 'grey' }}
/>
</View>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#FFCB43'
},
welcome: {
alignItems: 'center',
justifyContent: 'center',
padding: 10,
marginTop: 80,
},
buttonContainer: {
flex: 1,
alignItems: 'center',
justifyContent: 'space-evenly'
},
gameButton: {
height: 70,
width: Dimensions.get("screen").width / 1.4,
backgroundColor: 'red',
borderColor: 'red',
alignItems: 'center',
justifyContent: 'center',
borderRadius: 20,
borderWidth: 2,
borderColor: 'black',
},
text: {
fontSize: 22,
}
})
Some context and notices
The project was started on my friend's mac machine. According to him, he doesn't receive those errors. And he also was able to build the app into an .apk for Android
We are both using the same node.js version (15.11.0)
There are times when my metro fails to run, and when that happens, the app runs without any errors.
I have tried to build it into an .apk, but the build failed.
Before the app was combined into 3 games. They were individual games. The mole game did run and was built successfully into an .apk.
The mole game was forked from here The code is pretty much the same.
UPDATE :
After adding
componentWillUnmount(){
clearInterval(this.interval);
clearInterval(this.timerInterval);
}
to the App.js. I no longer get continuous "TypeError: null is not an object (evaluating '_this.moles[randomIndex].isPopping')". Unfortunately, I still get TypeError: null is not an object (evaluating '_this.moles.play) error. This happens when I go back to the main menu. I've tried adding clearTimeout(this.actionTimeout) on mole.js, but that didn't give any effect.
Screenshot :
TypeError: null is not an object (evaluating '_this.moles.play)
The setInterval() function is commonly used to set a delay for functions that are executed again and again, such as animations. You can cancel the interval using clearInterval().
When you navigate from MoleGame to Home, the MoleGame route is popped off the navigation stack and its component is unmounted. But the intervals from the setupTicks method are still executing, and trying to set state on the MoleGame component and to access this (neither of which are possible).
Try clearInterval on componentWillUnmount to stop the intervals that are set in the setupTicks method.
// App.js
export default class MoleGame extends Component {
constructor(props) {
super(props);
this.interval = null;
this.timeInterval = null;
...
}
componentDidMount = () => {
this.setupTicks(DEFAULT_STATE, this.pause);
}
componentWillUnmount() {
clearInterval(this.interval);
clearInterval(this.timeInterval);
}
}
Similarly in Mole.js you would have to handle the same scenario for any setTimeout()s you have by using clearTimeout()
Further reading: Plugging memory leaks in your app
By adding:
componentWillUnmount(){
clearInterval(this.interval);
clearInterval(this.timerInterval);
}
it fixed the continuous TypeError: null is not an object (evaluating '_this.moles[randomIndex].isPopping')
To remove the "TypeError: null is not an object (evaluating '_this.moles.play)" error, I had to put this.mole.play into a variable within Mole.js because this no longer refer to this.mole.play when I go back to the menu. There is still memory leak warnings since it is finishing the animation as I go to the menu, but there are no more critical errors.

Unable to resolve "constants/categories.json" from "screens\GridFilter\GridFilter.js"

I'm new at react-native and trying to build an app. When I try to run my code I'm getting this error................................................................
Failed building JavaScript bundle. Unable to resolve
"constants/categories.json" from "screens\GridFilter\GridFilter.js"
GridFilter.js:
import React from 'react';
import { StyleSheet, Text, View, FlatList, Dimensions, TouchableOpacity } from 'react-native';
import categories from 'constants/categories.json';
import filterIcons from 'components/Icons/filterIcons';
import { isIphoneX } from 'utils';
import fonts from 'theme/fonts';
const formatData = (data, numColumns) => {
const numberOfFullRows = Math.floor(data.length / numColumns);
let numberOfElementsLastRow = data.length - numberOfFullRows * numColumns;
while (numberOfElementsLastRow !== numColumns && numberOfElementsLastRow !== 0) {
data.push({ key: `blank-${numberOfElementsLastRow}`, empty: true });
numberOfElementsLastRow++;
}
return data;
};
const numColumns = 3;
const WIDTH = Dimensions.get('window').width;
function GridFilter({ navigation: { navigate } }) {
const renderItem = ({ item }) => {
if (item.empty === true) {
return <View style={[styles.item, styles.itemInvisible]} />;
}
const Icon = filterIcons[item.icon];
return (
<TouchableOpacity style={styles.item} onPress={() => navigate('SearchTopBarStack')}>
<View style={styles.iconWrapper}>
<Icon width={50} height={50} color="#9f9f9f" />
</View>
<Text style={styles.itemText}>{item.name}</Text>
</TouchableOpacity>
);
};
return (
<View style={styles.container}>
<FlatList
data={formatData(categories, numColumns)}
style={styles.wrapper}
renderItem={renderItem}
numColumns={numColumns}
contentContainerStyle={{ paddingBottom: 150 }}
/>
</View>
);
}
export default GridFilter;
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
paddingTop: isIphoneX ? 40 : 20,
},
wrapper: {
flex: 1,
},
iconWrapper: {
margin: 10,
},
item: {
alignItems: 'center',
justifyContent: 'center',
flex: 1,
height: WIDTH / numColumns, // approximate a square
padding: 20,
borderColor: 'gray',
borderWidth: 1,
borderRadius: 5,
backgroundColor: '#f3f3f3',
margin: 5,
},
itemInvisible: {
backgroundColor: 'transparent',
},
itemText: {
color: 'black',
textAlign: 'center',
fontFamily: fonts.REGULAR,
},
});
I tried to delete node modules and rebuild. What should I do?
You should refer to your current directory or file in your import. Try to use './' or '../' when you import path. If you use vscode it will give you auto completions.
"../../" is worked for me.

Attempt to invoke virtual method in React-Native

When i run my react native code it gives error and says:
Attempt to invoke virtual method 'com.facebook.react.bridge.CatalystInstance com.facebook.react.bridge.ReactContext.getCatalystInstance()' on a null object reference
but in case when I run my code the second time it does not show this type of error and code runs successfully. what is the reason behind this error? Please suggest any answer.
and my App.js files here..
import React, { Component } from 'react';
import { View, Text, StyleSheet, TouchableOpacity, Image, Platform, Animated } from 'react-native';
const Sliding_Drawer_Width = 300;
export default class App extends Component {
constructor()
{
super();
this.Animation = new Animated.Value(0);
this.Sliding_Drawer_Toggle = true;
}
ShowSlidingDrawer = () =>
{
if( this.Sliding_Drawer_Toggle === true )
{
Animated.timing(
this.Animation,
{
toValue: 1,
duration: 500
}
).start(() =>
{
this.Sliding_Drawer_Toggle = false;
});
}
else
{
Animated.timing(
this.Animation,
{
toValue: 0,
duration: 500
}
).start(() =>
{
this.Sliding_Drawer_Toggle = true;
});
}
}
render() {
const Animation_Interpolate = this.Animation.interpolate(
{
inputRange: [ 0, 1 ],
outputRange: [ -(Sliding_Drawer_Width - 32), 0 ]
});
return (
<View style = { styles.MainContainer }>
<Text style = {styles.TextStyle}> Components Which You Want To Show in App, Place Them Here. </Text>
<Animated.View style = {[ styles.Root_Sliding_Drawer_Container, { transform: [{ translateX: Animation_Interpolate }]}]}>
<View style = { styles.Main_Sliding_Drawer_Container }>
<Text style = { styles.TextStyle } > Put All Your Components Here Which You Want To Show Inside Sliding Drawer. </Text>
</View>
<TouchableOpacity onPress = { this.ShowSlidingDrawer } style = {{ padding: 1 }}>
<Image source = {{ uri : 'https://reactnativecode.com/wp-content/uploads/2017/11/Arrow_Icon.png' }} style = {{resizeMode: 'contain', width: 30, height: 30 }} />
</TouchableOpacity>
</Animated.View>
</View>
);
}
}
const styles = StyleSheet.create(
{
MainContainer:
{
flex: 1,
justifyContent: 'center',
alignItems: 'center'
},
Root_Sliding_Drawer_Container:
{
position: 'absolute',
flexDirection: 'row',
left: 0,
bottom: 0,
top: (Platform.OS == 'ios') ? 20 : 0,
width: Sliding_Drawer_Width,
},
Main_Sliding_Drawer_Container:
{
flex: 1,
backgroundColor: '#FFC107',
paddingHorizontal: 10,
justifyContent: 'center',
alignItems: 'center'
},
TextStyle: {
fontSize: 25,
padding: 10,
textAlign: 'center',
color: '#FF5722'
}
});

Building a Tic-Tac-Toe Game in React Native adding Styles

I am building a tic-tac-toe game and need to know how I can add an individual style to an individual board piece. If I am using state, would I need a variable that represents each piece on the board? Is there more of an elegant way of doing this. I posted my code here, just give you an idea on how it looks.
import React, { Component } from 'react';
import { ListView, StyleSheet, Text, View, TouchableOpacity } from 'react-native';
class MainApp extends Component {
state = {
clicked: true,
spacePlayed: [],
tables: [0, 1, 2, 3, 4, 5, 6, 7, 8],
playedSpace: [],
}
searchBoard = (index) => {}
_setBoard = (tableId) => {
this.setState({
clicked: !this.state.clicked,
});
var spacePlayed = this.state.playedSpace.push(tableId);
this.setState({ spacePlayed });
}
buildBoard = () => {
var clicked = false;
return (this.state.tables.map((table, index) => {
if (index === 0) {
return (
<TouchableOpacity key={index} onPress={() => this._setBoard(index)}>
<View style={styles.table}></View>
</TouchableOpacity>
);
} else {
return (
<TouchableOpacity key={index} onPress={() => this._setBoard(index)}>
<View style={styles.tableActive}></View>
</TouchableOpacity>
);
}
}));
}
render() {
const active = this.state.clicked
? styles.active
: null;
return (
<View style={styles.container}>
{this.buildBoard()}
</View>
);
}
}
var styles = StyleSheet.create({
container: {
flexWrap: 'wrap',
flexDirection: 'row',
width: 200,
justifyContent: 'center',
alignItems: 'center',
marginLeft: 70,
marginTop: 20,
},
table: {
height: 50,
width: 50,
backgroundColor: '#78BEC5',
margin: 5,
justifyContent: 'center',
alignItems: 'center',
},
active: {
backgroundColor: '#ECAF4F',
},
tableActive: {
height: 50,
width: 50,
backgroundColor: '#ECAF4F',
margin: 5,
justifyContent: 'center',
alignItems: 'center',
},
});
export default MainApp;

How to show text (YES/NO) inside a switch in react-native

I am new to react-native. In my app, I'm using a switch and changing the tint color to differentiate ON and OFF, but my actual requirement is to show "YES" or "NO" text inside the switch like below.
Here is my Code:
<Switch
onValueChange={this.change.bind(this)}
style={{marginBottom:10,width:90,marginRight:6,marginLeft:6}}
value={true}
thumbTintColor="#0000ff"
tintColor="#ff0000"
/>
Please give me suggestions to solve this issue, Any help much appreciated.
Finally I got the On off inside switch .......
install
npm install --save react-native-switch
import { Switch } from 'react-native-switch';
<Switch
value={true}
onValueChange={(val) => console.log(val)}
disabled={false}
activeText={'On'}
inActiveText={'Off'}
backgroundActive={'green'}
backgroundInactive={'gray'}
circleActiveColor={'#30a566'}
circleInActiveColor={'#000000'}/>
Refer this link...
https://github.com/shahen94/react-native-switch
I would start with something like this and then iterate and polish until it fulfills the requirements and looks good. This isn't a complete solution but should give you some ideas.
import React from 'react';
import { LayoutAnimation, StyleSheet, Text, TouchableOpacity, View } from 'react-native';
const styles = StyleSheet.create({
container: {
width: 80,
height: 30,
backgroundColor: 'grey',
flexDirection: 'row',
overflow: 'visible',
borderRadius: 15,
shadowColor: 'black',
shadowOpacity: 1.0,
shadowOffset: {
width: -2,
height: 2,
},
},
circle: {
width: 34,
height: 34,
borderRadius: 17,
backgroundColor: 'white',
marginTop: -2,
shadowColor: 'black',
shadowOpacity: 1.0,
shadowOffset: {
width: 2,
height: 2,
},
},
activeContainer: {
backgroundColor: 'blue',
flexDirection: 'row-reverse',
},
label: {
alignSelf: 'center',
backgroundColor: 'transparent',
paddingHorizontal: 6,
fontWeight: 'bold',
},
});
class LabeledSwitch extends React.Component {
constructor(props) {
super(props);
this.state = {
value: props.value,
};
this.toggle = this.toggle.bind(this);
}
componentWillReceiveProps(nextProps) {
// update local state.value if props.value changes....
if (nextProps.value !== this.state.value) {
this.setState({ value: nextProps.value });
}
}
toggle() {
// define how we will use LayoutAnimation to give smooth transition between state change
LayoutAnimation.configureNext(LayoutAnimation.Presets.spring);
const newValue = !this.state.value;
this.setState({
value: newValue,
});
// fire function if exists
if (typeof this.props.onValueChange === 'function') {
this.props.onValueChange(newValue);
}
}
render() {
const { value } = this.state;
return (
<TouchableOpacity onPress={this.toggle}>
<View style={[
styles.container,
value && styles.activeContainer]}
>
<View style={styles.circle} />
<Text style={styles.label}>
{ value ? 'YES' : 'NO' }
</Text>
</View>
</TouchableOpacity>
);
}
}
LabeledSwitch.propTypes = {
onValueChange: React.PropTypes.func,
value: React.PropTypes.bool,
};
LabeledSwitch.defaultProps = {
};
export default LabeledSwitch;