I am having an issue where I have created two components "TaskInputField.js" and "TaskItem.js" and when I import them into the file I want to use them in, the browser window I am viewing the app on turns completely blank (using expo). Can post screenshots of what I mean if needed.
This has never happened to me before where simply importing a file breaks the application.
If I remove the imports from GroceryList.js and remove where I use them in the file, everything else runs just fine. I followed a guide for most of this also so I am unsure what is happening.
Thanks in advance.
For reference:
TaskInputField.js
import React, {useState} from 'react';
import { KeyboardAvoidingView, StyleSheet, View, TextInput, TouchableOpacity, } from "react-native";
import { MaterialIcons } from '#expo/vector-icons';
export default TaskInputField = (props) => {
const [task, setTask] = useState();
const handleAddTask = (value) => {
props.addTask(value);
setTask(null);
}
return (
<KeyboardAvoidingView
behavior={Platform.OS === "ios" ? "padding" : "height"}
style={styles.container}
>
<TextInput style={styles.inputField} value={task} onChangeText={text => setTask(text)} placeholder={'Write a task'} placeholderTextColor={'#fff'}/>
<TouchableOpacity onPress={() => handleAddTask(task)}>
<View style={styles.button}>
<MaterialIcons name="keyboard-arrow-up" size={24} color="black" />
</View>
</TouchableOpacity>
</KeyboardAvoidingView>
);
}
TaskItem.js
import React from 'react';
import { StyleSheet, Text, View, TouchableOpacity, } from "react-native";
import { MaterialIcons } from '#expo/vector-icons';
export default TaskItem = (props) => {
return (
<View style={styles.container}>
<View style={styles.indexContainer}>
<Text style={styles.index}>{props.index}</Text>
</View>
<View style={styles.taskContainer}>
<Text style={styles.task}>{props.task}</Text>
<TouchableOpacity onPress={() => props.deleteTask()}>
<MaterialIcons style={styles.delete} name="delete" size={18} color='#fff' />
</TouchableOpacity>
</View>
</View>
);
}
I am implementing these here in GroceryList.js
import React, {useState} from 'react';
import { Keyboard, ScrollView, StyleSheet, Text, View } from 'react-native';
import TaskInputField from '../../components/TaskInputField';
import TaskItem from '../../components/TaskItem';
export default function GroceryList() {
const [tasks, setTasks] = useState([]);
const addTask = (task) => {
if (task == null) return;
setTasks([...tasks, task]);
Keyboard.dismiss();
}
const deleteTask = (deleteIndex) => {
setTasks(tasks.filter((value, index) => index != deleteIndex));
}
return(
<View style={styles.container}>
<Text style={styles.heading}>Grocery List</Text>
<ScrollView style={styles.scrollView}>
{
tasks.map((task, index) => {
return (
<View key={index} style={styles.taskContainer}>
<TaskItem index={index + 1} task={task} deleteTask={() => deleteTask(index)}/>
</View>
);
})
}
</ScrollView>
<TaskInputField addTask={addTask}/>
</View>
)
}
Related
I'm trying to use Async Storage for a note app, I created a component called task.js as a template for todos, an navigation.js component for nav, and home.js for the main screen all display with <navigation /> inapp.js, I added a funcction to store object value using async storage, but is not working, everytime I hard reload the app everything will be gone but it is not giving me any errors, I don't know where to start
here is my Home.js
import React, {useState} from 'react';
import { Keyboard, KeyboardAvoidingView, Platform, StyleSheet, Text,
TextInput, TouchableOpacity, View, SafeAreaView, ScrollView, Image } from 'react-native';
import Task from '../components/Task';
import AsyncStorage from '#react-native-async-storage/async-storage';
export default function Home({ navigation }) {
const [task, setTask] = useState();
const [taskItems, setTaskItems] = useState([]);
React.useEffect ( () => {
save(taskItems);
}, [taskItems])
React.useEffect (() => {
getsave();
}, [])
const handleAddTask = () => {
Keyboard.dismiss();
setTaskItems([...taskItems, task])
setTask(null);
}
const completeTask = (index) => {
let itemsCopy = [...taskItems];
itemsCopy.splice (index, 1);
setTaskItems(itemsCopy)
}
const save = async taskItems =>{
try {
const savetask = JSON.stringify(taskItems)
await AsyncStorage.setItem('tasksave', savetask)
} catch (e) {
console.log(e);
}
};
const getsave = async () => {
try {
const taskItems = await AsyncStorage.getItem('tasksave');
if (taskItems != null){
setTaskItems(JSON.parse(taskItems));
}
} catch (error) {
console.log(e);
}
};
return (
<SafeAreaView style={styles.container}>
<View style={styles.tasksWrapper}>
<Text style={styles.sectionTitle}>Your stuff:</Text>
<TouchableOpacity onPress={() => navigation.navigate('About')}>
<Text style={styles.about}>About</Text>
</TouchableOpacity>
<ScrollView style={styles.items}>{
taskItems.map((item, index) => {
return (
<View key={index}>
<TouchableOpacity onPress={ () => navigation.navigate("Gas", {item})}>
<Task text={item} navigation={navigation} />
</TouchableOpacity>
<TouchableOpacity onPress={() => completeTask(index)} style={styles.deleteW}>
<Image style={styles.delete} source={require('../components/remove.png')}></Image>
</TouchableOpacity>
</View>
)
})
}
</ScrollView>
</View>
<KeyboardAvoidingView
behavior={Platform.OS === "ios" ? "padding" : "height"}
style={styles.textwrapper}>
<TextInput style={styles.input} placeholder={'message'} value={task} onChangeText={text => setTask(text)}></TextInput>
<TouchableOpacity onPress={() => handleAddTask()}>
<View style={styles.addWrap}>
<Text style={styles.add}>+</Text>
</View>
</TouchableOpacity>
</KeyboardAvoidingView>
</SafeAreaView>
);
}
Here's my Task.js:
import React from "react";
import { View, Text, StyleSheet, Image, TouchableOpacity } from "react-native";
const Task = (props, {navigation}) => {
return (
<View style={styles.item}>
<View style={styles.itemleft}>
<Image style={styles.lightball} source={require('./arabic.png')}></Image>
<Text style={styles.itemtext}>{props.text}</Text>
</View>
<Image style={styles.arrow} source={require('./rightarrow.png')}></Image>
</View>
)
}
const styles = StyleSheet.create({
export default Task;
I hope is a quick read, I took out all the style stuff but this is still kinda long sorry, if you think it has something to do with my app.js or nav.js I can give you those too, I usually slove these bugs on my own but I just have no idea where to begin cause I'm not getting any error messages, thank you
I'm new to React Native. I need that if I click on a button, a new page appears. I already tried a few things but maybe the problem is somewhere else.
I will paste my code underneath. Please help me :)
Further explanation: I want to click on the button and then it should go to another page.
import React, { useState } from "react";
import {
StyleSheet,
Text,
View,
Image,
TextInput,
TouchableOpacity,
Linking,
Button
} from "react-native";
import { useNavigation } from '#react-navigation/native';
import "react-native-gesture-handler";
import { NavigationContainer } from '#react-navigation/native';
import { createStackNavigator, createAppContainer } from 'react-navigation';
export default function App() {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
return (
<View style={styles.container}>
<Image style={styles.image} source={require("./assets/logo.png")} />
<StatusBar style="auto" />
<View style={styles.inputView}>
<TextInput
style={styles.TextInput}
placeholder="Benutzername"
onChangeText={(email) => setEmail(email)}
/>
</View>
<Button
style={styles.loginBtn}
title="Go to Profile"
onPress={() => this.props.navigation.navigate('Profile')}
/>
</View>
);
}
```
Might be this helpful to you:
MyNavigation Version
#react-navigation/native": "^5.9.8"
#react-navigation/stack": "^5.14.9"
Example
import React from 'react';
import {View, Text, StyleSheet, TouchableOpacity} from 'react-native';
//Navigation import
import {NavigationContainer} from '#react-navigation/native';
import {createStackNavigator} from '#react-navigation/stack';
//Screen One
const ScreenOne = props => {
//onPress To Navigate
const onPress = () => {
props.navigation.navigate('ScreenTwo');
};
return (
<View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
<TouchableOpacity onPress={onPress}>
<Text>Hello From Screen One</Text>
</TouchableOpacity>
</View>
);
};
//Screen Two
const ScreenTwo = () => {
return (
<View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
<Text>Screen Two</Text>
</View>
);
};
const App = () => {
//const
const Stack = createStackNavigator();
return (
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen name="ScreenOne" component={ScreenOne} />
<Stack.Screen name="ScreenTwo" component={ScreenTwo} />
</Stack.Navigator>
</NavigationContainer>
);
};
export default App;
I'm trying to learning about chat app using expo-react native-typescript. What im doing so far is like below :
ChatRoomScreen.tsx
import React, { useState, useRef, useEffect } from 'react';
import { StyleSheet, Text, View, FlatList, SafeAreaView, ActivityIndicator } from 'react-native'
import { useRoute, useNavigation } from '#react-navigation/core'
import Message from '../components/Message'
import MessageInput from '../components/MessageInput'
// api client
import axios from 'axios';
const ChatRoomScreen = () => {
const route = useRoute()
const mounted = useRef(true);
const roomID = route.params?.id
const user = route.params?.user
const isMe = route.params?.isMe
const [message, setMessage] = useState();
//AxiosRequest
//get chats
const fetchMessages = async () =>{
axios.get('https://mylaravelAPI.com/api/get/'+roomID)
.then(function (response) {
// handle success
const result = response.data.message.reverse();
{setMessage(result)}
})
}
useEffect(() => {
fetchMessages()
},[])
return (
<SafeAreaView style={styles.page}>
<FlatList
data={message}
//Send params to Message
renderItem={({item}) => <Message message={item} roomID={roomID}/> }
inverted
/>
<MessageInput
//Send params to MessageInput
id={route.params?.id}
receiveID={route.params?.user}
userID={route.params?.isMe}
/>
</SafeAreaView>
)
}
export default ChatRoomScreen
Message.tsx
import React from 'react'
import { StyleSheet, Text, View } from 'react-native'
const blue = '#3777f0'
const grey = 'lightgrey'
const myID = '1'
const Message = ({ message, roomID }) => {
const isMe = message.user.id == myID
const roomId = roomID
return (
<View style={[
styles.container, isMe ? styles.rightContainer : styles.leftContainer]}
>
<Text style={{ color: isMe ? 'black' : 'white' }}>{message.content}</Text>
</View>
)
}
export default Message
MessageInput.tsx
import React, { useState, useEffect } from 'react'
import { StyleSheet, Text, View, TextInput, Pressable } from 'react-native'
import { SimpleLineIcons, Feather, MaterialCommunityIcons, AntDesign, Ionicons } from '#expo/vector-icons'
import MessageComponent from "../Message";
// api client
import axios from 'axios';
const MessageInput = ({id, receiveID, userID}) => {
const [message, setMessage] = useState()
const chatroom = id
const senderUserID = userID.id
const receiveUserID = receiveID.id
//Action
//save message
const saveMessage = () => {
axios({
method: 'post',
url: 'https://mylaravelAPI.com/api/post',
headers: {
'content-type': 'application/json',
},
data: JSON.stringify({
"content": message,
"userID": senderUserID,
"replyToID": receiveUserID
})
});
setMessage('')
}
//update message
const updateMessage = () => {
console.log('updateMessage')
}
//OnPress
const onPress2 = () => {
if (chatroom === null) {
{saveMessage()}
}else{
{updateMessage()}
}
}
const onPress = () => {
// console.log(message)
}
return (
<View style={styles.root}>
<View style={styles.inputContainer}>
<SimpleLineIcons name='emotsmile' size={24} color='#595959' style={styles.icon}/>
<TextInput
style={styles.input}
value={message}
onChangeText={setMessage}
placeholder="Signal message..."
/>
<Feather name='camera' size={24} color='#595959' style={styles.icon}/>
<MaterialCommunityIcons name='microphone-outline' size={24} color='#595959' style={styles.icon}/>
</View>
{/* <Pressable onPress={onPress} style={styles.buttonContainer}>
{message ? <Ionicons name="send" size={18} color="white" /> : <AntDesign name='plus' size={24} color='white' />}
</Pressable> */}
<View onPress={onPress} style={styles.buttonContainer}>
{message ?
<Pressable
onPress={onPress2}>
<Ionicons name="send" size={18} color="white" />
</Pressable> :
<Pressable
onPress={onPress}>
<AntDesign name='plus' size={24} color='white' />
</Pressable>
}
</View>
</View>
)
}
export default MessageInput
Everything is working except the message not update or shows ini realtime. It's will show only when i go back to Welcome screen and open the chat/room again... please help me.. thanks
I am following this module on Alex Macmillian's Udemy COurse on react native:
In the 65th module, I am getting this error :
error screenshot
import React, { useState } from "react";
import {
View,
StyleSheet,
Text,
TouchableWithoutFeedback,
Keyboard,
Dimensions,
Alert,
TouchableOpacity,
} from "react-native";
import Card from '../components/Card'
import Colors from '../constants/Colors'
import Input from '../components/Input'
import CircleShape from '../components/CircleShape'
import HeartShape from '../components/HeartShape'
import CrossShape from '../components/CrossShape'
const StartGameScreen = props => {
const [enteredValue, setEnteredValue] = useState('')
const [selectedNumber, setSelectedNumber] = useState()
const [confirmed, setConfirmed] = useState(false);
//validates the non valid inputs in the inputText
const changeTextHandler = inputText => {
//replaces any character other than 0-9 with a blank
setEnteredValue(inputText.replace(/[^0-9]/g, ''))
}
const resetInputHandler = () => {
setEnteredValue('');
Keyboard.dismiss()
setConfirmed(false)
}
const confirmInputHandler = () => {
const chosenNumber = parseInt(enteredValue);
if (isNaN(chosenNumber) || chosenNumber <= 0 || chosenNumber > 99) {
Alert.alert('Invalid String!', "Enter a number between 0 and 99",
[{ text: "Okay", style: "default", onPress: resetInputHandler },
{ text: 'Cancel', style: 'destructive', onPress: resetInputHandler }])
return;
}
setConfirmed(true);
setSelectedNumber(chosenNumber)
setEnteredValue('')
Keyboard.dismiss()
}
let confirmedOutput;
if (confirmed) {
// confirmedOutput = <Text> You Chose : {selectedNumber} </Text>
confirmedOutput = (
<Card style={styles.circleShapeView}>
<Text style={styles.selectedNumber}>{selectedNumber}</Text>
<TouchableOpacity
activeOpacity={0.26}
style={styles.TriangleShapeView}
onPress={() => props.onStartGame(selectedNumber)}>
</TouchableOpacity>
</Card>
)
}
return (
<TouchableWithoutFeedback onPress={() => {
Keyboard.dismiss()
}}>
<View style={styles.screen}>
<Card style={styles.gameArea}>
<Input
style={styles.textInput}
keyboardType="numeric"
maxLength={2}
onChangeText={changeTextHandler}
value={enteredValue}
placeholder='0'
placeholderTextColor="#000" />
{/* <View style={styles.buttonContainer}>
<View style={styles.button}>
<Button
onPress={resetInputHandler}
title="Reset"
color="#fff" />
</View>
<View style={styles.button}>
<Button
title="Confirm"
color="#fff"
onPress={confirmInputHandler} />
</View>
</View> */}
<View style={styles.buttonContainer}>
<TouchableOpacity style={styles.heartButton} onPress={resetInputHandler}>
<CircleShape style={styles.circle}>
<HeartShape style={styles.heart}>
</HeartShape>
</CircleShape>
</TouchableOpacity>
<TouchableOpacity style={styles.crossButton} onPress={confirmInputHandler}>
<CircleShape style={styles.circle}>
<CrossShape style={styles.cross}></CrossShape>
</CircleShape>
</TouchableOpacity>
</View>
</Card>
{confirmedOutput}
</View>
</TouchableWithoutFeedback>
);
}
export default StartGameScreen;
The App.js file -->
import React, { useState } from 'react';
import { StyleSheet, View } from 'react-native';
import Header from './components/Header'
import StartGameScreen from './screens/StartGameScreen'
import GameScreen from './screens/GameScreen';
export default function App() {
const [userNumber, setUserNumber] = useState();
const startGameHandler = selectedNumber => {
setUserNumber(selectedNumber);
}
let screen = <StartGameScreen onStartGame={startGameHandler} />;
if (userNumber) {
screen = <GameScreen userChoice={userNumber}/>
}
return (
<View style={styles.screen}>
<Header title="Guessie"></Header>
<StartGameScreen></StartGameScreen>
</View>
);
}
const styles = StyleSheet.create({
screen: {
flex:1
},
});
How do i fix this error?
Type Error: props.onStartGame is not a function. (IN 'props.onStartGame(selectedNUmber)','props.onStartGame' is undefined)
You need to pass screen variable instead of <StartGameScreen></StartGameScreen> ,
if first approach doesn't work trying passing the onStartGame={startGameHandler} like this in your code <Header title="Guessie"></Header>
<StartGameScreen onStartGame={startGameHandler} >
</StartGameScreen>
if (isNaN(chosenNumber) || chosenNumber <= 0 || chosenNumber > 99) {
Alert.alert(
'Invalid number!',
'Number has to be a number between 1 and 99.',
[{ text: 'Okay', style: 'destructive', onPress: resetInputHandaler }]
);
I am currently learning React Native and was having some issue with React-navigation.
What I am trying to do is switch screen when the "button" is being pressed.
In the "button", I have:
onPress={() =>
navigate('Home')}
I have const { navigate } = this.props.navigation; before the return statement.
When I run it, I am getting "Cannot read property 'navigate' of undefined.
I guess it is I have to place this.props.navigation somewhere.
Here are my two files:
"IntroPageFive" is the one that has the button and "react-navigation".
I would like to go to "IntroPageOne" when the button is being clicked.
Code for "IntroPageFive":
import React from 'react';
import { Text, View, Image, Linking, Button, TouchableOpacity } from 'react-native';
import PlaceholderImage from '../images/placeholder_thumbnail.png';
import SignInFooter from './signInFooter';
import { createStackNavigator } from 'react-navigation';
import IntroPageOne from './introPageOne';
const App = createStackNavigator({
Home: { screen: IntroPageOne },
});
class IntroPageFive extends React.Component {
render() {
const {
headerTextStyle,
thumbnailStyle,
viewStyle,
subTextStyle,
mainTextSection,
footerSectionStyle,
startButtonStyle,
startButtonTextStyle,
signInButtonStyle ,
signInButtonTextStyle
} = styles;
const { navigate } = this.props.navigation;
return (
<View style={viewStyle}>
<Image style={thumbnailStyle} source={require('../images/placeholder_thumbnail.png')} />
<View style={mainTextSection}>
<Text style={headerTextStyle}>Take A Ride For</Text>
<Text style={headerTextStyle}>Your Favorite Car!</Text>
</View>
<View>
<TouchableOpacity
onPress={() =>
navigate('Home')
}
style={startButtonStyle}
>
<Text style={startButtonTextStyle}>LET'S GET STARTED</Text>
</TouchableOpacity>
</View>
<View style={footerSectionStyle}>
<SignInFooter />
</View>
</View>
);
}
}
export default IntroPageFive;
Here is the code for "IntroPageOne":
import React from 'react';
import { Text, View, Image, Linking } from 'react-native';
import PlaceholderImage from '../images/placeholder_thumbnail.png';
import SignInFooter from './signInFooter';
const IntroPageOne = () => {
const { headerTextStyle, thumbnailStyle, viewStyle, subTextStyle } = styles;
return (
<View style={viewStyle} >
<Image style={thumbnailStyle} source={require('../images/placeholder_thumbnail.png')} />
<Text style={headerTextStyle}>Forget Everything You</Text>
<Text style={headerTextStyle}>Know About Making</Text>
<Text style={headerTextStyle}>Deals For Your Car</Text>
<Text style={subTextStyle}>Deal negotiation powered by AI</Text>
<SignInFooter />
</View>
);
};
};
export default IntroPageOne;
Could anyone please tell me how to fix this issue?
Thank you.