// App.tsx import React, { useState, useEffect } from 'react'; import {…
- User
// App.tsx
import React, { useState, useEffect } from 'react'; import { NavigationContainer, CommonActions } from '@react-navigation/native'; import { createStackNavigator } from '@react-navigation/stack'; import { createBottomTabNavigator } from '@react-navigation/bottom-tabs'; import { View, StyleSheet, Platform, TouchableOpacity, Keyboard } from 'react-native'; import HomeScreen from './src/screens/HomeScreen'; import ChatListScreen from './src/screens/ChatListScreen'; import ChatScreen from './src/screens/ChatScreen'; import { Ionicons } from '@expo/vector-icons'; import CustomText from './src/components/CustomText'; import { ChatProvider } from './src/context/ChatContext'; // Import ChatProvider
const Stack = createStackNavigator(); const Tab = createBottomTabNavigator();
const ChatStack = () => ( <Stack.Navigator initialRouteName="ChatList" screenOptions={{ headerShown: false, }}
<Stack.Screen name="ChatList" component={ChatListScreen} /><Stack.Screen name="Chat" component={ChatScreen} /></Stack.Navigator> );
const FiguresStack = () => ( <Stack.Navigator initialRouteName="Home" screenOptions={{ headerShown: false, }}
<Stack.Screen name="Home" component={HomeScreen} /></Stack.Navigator> );
const TabBar = ({ state, descriptors, navigation }) => { const [isKeyboardVisible, setKeyboardVisible] = useState(false);
useEffect(() => { const showSubscription = Keyboard.addListener('keyboardDidShow', () => { setKeyboardVisible(true); }); const hideSubscription = Keyboard.addListener('keyboardDidHide', () => { setKeyboardVisible(false); });
return () => { showSubscription.remove(); hideSubscription.remove(); };}, []);
if (isKeyboardVisible) { return null; // Hide the TabBar when the keyboard is visible }
return ( {state.routes.map((route, index) => { const { options } = descriptors[route.key]; const label = options.tabBarLabel !== undefined ? options.tabBarLabel : options.title !== undefined ? options.title : route.name;
const isFocused = state.index === index; const onPress = () => { const event = navigation.emit({ type: 'tabPress', target: route.key, canPreventDefault: true, }); if (!isFocused && !event.defaultPrevented) { navigation.navigate(route.name); } }; // Render the icon directly without extracting 'name' const icon = options.tabBarIcon ? options.tabBarIcon({ focused: isFocused, color: isFocused ? '#007AFF' : '#8E8E93', size: 24, }) : null; return ( <TouchableOpacity key={route.key} accessibilityRole="button" accessibilityState={isFocused ? { selected: true } : {}} accessibilityLabel={options.tabBarAccessibilityLabel} testID={options.tabBarTestID} onPress={onPress} style={styles.tabItem} > {icon} <CustomText style={[styles.tabLabel, { color: isFocused ? '#007AFF' : '#8E8E93' }]}> {label} </CustomText> </TouchableOpacity> ); })} </View>); };
const App = () => { return ( {/* Wrap NavigationContainer with ChatProvider */} <Tab.Navigator initialRouteName="Figures" tabBar={(props) => <TabBar {...props} />} screenOptions={({ route }) => ({ headerShown: false, tabBarIcon: ({ focused, color, size }) => { let iconName = ''; if (route.name === 'Figures') { iconName = focused ? 'people' : 'people-outline'; } else if (route.name === 'Chats') { iconName = focused ? 'chatbubbles' : 'chatbubbles-outline'; } return ; }, })} > <Tab.Screen name="Figures" component={FiguresStack} options={{ tabBarLabel: 'Karakterler', }} /> <Tab.Screen name="Chats" component={ChatStack} options={{ tabBarLabel: 'Sohbetler', }} listeners={({ navigation, route }) => ({ tabPress: e => { // Prevent default behavior e.preventDefault();
// Reset the navigation stack to ChatList navigation.dispatch( CommonActions.reset({ index: 0, routes: [{ name: 'Chats', state: { routes: [{ name: 'ChatList' }] } }], }) ); }, })} /> </Tab.Navigator> </NavigationContainer> </ChatProvider>); };
const styles = StyleSheet.create({ tabContainer: { flexDirection: 'row', backgroundColor: '#F8F8F8', borderTopWidth: 1, borderTopColor: '#E0E0E0', paddingBottom: Platform.OS === 'ios' ? 20 : 10, paddingTop: 10, }, tabItem: { flex: 1, alignItems: 'center', justifyContent: 'center', }, tabLabel: { fontSize: 12, marginTop: 3, fontFamily: 'Poppins_400Regular', }, });
export default App; // src/context/ChatContext.tsx
import React, { createContext, useState, useEffect, useCallback } from 'react'; import AsyncStorage from '@react-native-async-storage/async-storage'; import { Chat, Message } from '../types/types';
interface ChatWithLastMessage extends Chat { lastMessage?: string; lastMessageTimestamp?: number; }
interface ChatContextProps { chats: ChatWithLastMessage[]; addChat: (chat: Chat, message: Message) => Promise; updateChat: (chatId: string, message: Message) => Promise; deleteChat: (chatId: string) => Promise; deleteAllChats: () => Promise; }
export const ChatContext = createContext({ chats: [], addChat: async () => {}, updateChat: async () => {}, deleteChat: async () => {}, deleteAllChats: async () => {}, });
export const ChatProvider: React.FC = ({ children }) => { const [chats, setChats] = useState<ChatWithLastMessage[]>([]);
// Load chats from AsyncStorage on mount useEffect(() => { const loadChats = async () => { try { const chatsData = await AsyncStorage.getItem('chats'); const chatsList: Chat[] = chatsData ? JSON.parse(chatsData) : [];
const chatsWithMessages: ChatWithLastMessage[] = await Promise.all( chatsList.map(async (chat) => { const messagesData = await AsyncStorage.getItem(`chat_${chat.id}_messages`); const messages: Message[] = messagesData ? JSON.parse(messagesData) : []; const lastMessage = messages[messages.length - 1]?.text || ''; const lastTimestamp = messages[messages.length - 1]?.timestamp || chat.createdAt; return { ...chat, lastMessage, lastMessageTimestamp: lastTimestamp, }; }) ); const sortedChats = chatsWithMessages.sort( (a, b) => (b.lastMessageTimestamp || 0) - (a.lastMessageTimestamp || 0) ); setChats(sortedChats); } catch (error) { console.error('Error loading chats:', error); } }; loadChats();}, []);
// Add a new chat const addChat = useCallback(async (chat: Chat, message: Message) => { try { const newChat: ChatWithLastMessage = { ...chat, lastMessage: message.text, lastMessageTimestamp: message.timestamp, }; const updatedChats = [...chats, newChat]; setChats(updatedChats); await AsyncStorage.setItem('chats', JSON.stringify(updatedChats)); await AsyncStorage.setItem(
chat_${chat.id}_messages, JSON.stringify([message])); } catch (error) { console.error('Error adding chat:', error); } }, [chats]);// Update an existing chat with a new message const updateChat = useCallback(async (chatId: string, message: Message) => { try { // Retrieve existing messages const messagesData = await AsyncStorage.getItem(
chat_${chatId}_messages); const messages: Message[] = messagesData ? JSON.parse(messagesData) : []; const updatedMessages = [...messages, message]; await AsyncStorage.setItem(chat_${chatId}_messages, JSON.stringify(updatedMessages));// Update chat's last message and timestamp setChats((prevChats) => { const updatedChats = prevChats.map((chat) => { if (chat.id === chatId) { return { ...chat, lastMessage: message.text, lastMessageTimestamp: message.timestamp, }; } return chat; }).sort((a, b) => (b.lastMessageTimestamp || 0) - (a.lastMessageTimestamp || 0)); // Persist updated chats AsyncStorage.setItem('chats', JSON.stringify(updatedChats)).catch((err) => console.error('Error updating chats in AsyncStorage:', err) ); return updatedChats; }); } catch (error) { console.error('Error updating chat:', error); }}, []);
// Delete a specific chat const deleteChat = useCallback(async (chatId: string) => { try { const updatedChats = chats.filter((chat) => chat.id !== chatId); setChats(updatedChats); await AsyncStorage.setItem('chats', JSON.stringify(updatedChats)); await AsyncStorage.removeItem(
chat_${chatId}_messages); } catch (error) { console.error('Error deleting chat:', error); } }, [chats]);// Delete all chats const deleteAllChats = useCallback(async () => { try { setChats([]); await AsyncStorage.removeItem('chats'); const keys = await AsyncStorage.getAllKeys(); const chatMessageKeys = keys.filter( (key) => key.startsWith('chat_') && key.endsWith('_messages') ); await AsyncStorage.multiRemove(chatMessageKeys); } catch (error) { console.error('Error deleting all chats:', error); } }, []);
return ( <ChatContext.Provider value={{ chats, addChat, updateChat, deleteChat, deleteAllChats }}> {children} {/* Ensure only children are rendered */} </ChatContext.Provider> ); };
ERROR Warning: Error: Text strings must be rendered within a component.
This error is located at: in ChatProvider (created by App) in App (created by withDevTools(App)) in withDevTools(App) in RCTView (created by View) in View (created by AppContainer) in RCTView (created by View) in View (created by AppContainer) in AppContainer in main(RootComponent), js engine: hermes
bu hatayı düzelt kodları eksiksiz geri yolla
- Assistant
The error you're encountering:
Warning: Error: Text strings must be rendered within a <Text> component.indicates that somewhere in your component tree, a plain text string is being rendered directly inside a
Viewor another non-Textcomponent without being wrapped in a<Text>component.Based on the code you've shared, the primary issue is that both
App.tsxandChatContext.tsxare combined into a single file. This causes theChatContext.tsxcode to be interpreted as plain text withinApp.tsx, leading to the error.To resolve this, you need to separate the
App.tsxandChatContext.tsxinto individual files. Below are the corrected and separated versions of both files:
1.
App.tsxThis file sets up the navigation and integrates the
ChatProvider. Ensure that this file only contains the following code:// App.tsx import React from 'react'; import { NavigationContainer, CommonActions } from '@react-navigation/native'; import { createStackNavigator } from '@react-navigation/stack'; import { createBottomTabNavigator } from '@react-navigation/bottom-tabs'; import { View, StyleSheet, Platform, TouchableOpacity, Keyboard } from 'react-native'; import HomeScreen from './src/screens/HomeScreen'; import ChatListScreen from './src/screens/ChatListScreen'; import ChatScreen from './src/screens/ChatScreen'; import { Ionicons } from '@expo/vector-icons'; import CustomText from './src/components/CustomText'; import { ChatProvider } from './src/context/ChatContext'; // Import ChatProvider const Stack = createStackNavigator(); const Tab = createBottomTabNavigator(); const ChatStack = () => ( <Stack.Navigator initialRouteName="ChatList" screenOptions={{ headerShown: false, }} > <Stack.Screen name="ChatList" component={ChatListScreen} /> <Stack.Screen name="Chat" component={ChatScreen} /> </Stack.Navigator> ); const FiguresStack = () => ( <Stack.Navigator initialRouteName="Home" screenOptions={{ headerShown: false, }} > <Stack.Screen name="Home" component={HomeScreen} /> </Stack.Navigator> ); const TabBar = ({ state, descriptors, navigation }) => { const [isKeyboardVisible, setKeyboardVisible] = React.useState(false); React.useEffect(() => { const showSubscription = Keyboard.addListener('keyboardDidShow', () => { setKeyboardVisible(true); }); const hideSubscription = Keyboard.addListener('keyboardDidHide', () => { setKeyboardVisible(false); }); return () => { showSubscription.remove(); hideSubscription.remove(); }; }, []); if (isKeyboardVisible) { return null; // Hide the TabBar when the keyboard is visible } return ( <View style={styles.tabContainer}> {state.routes.map((route, index) => { const { options } = descriptors[route.key]; const label = options.tabBarLabel !== undefined ? options.tabBarLabel : options.title !== undefined ? options.title : route.name; const isFocused = state.index === index; const onPress = () => { const event = navigation.emit({ type: 'tabPress', target: route.key, canPreventDefault: true, }); if (!isFocused && !event.defaultPrevented) { navigation.navigate(route.name); } }; // Render the icon directly without extracting 'name' const icon = options.tabBarIcon ? options.tabBarIcon({ focused: isFocused, color: isFocused ? '#007AFF' : '#8E8E93', size: 24, }) : null; return ( <TouchableOpacity key={route.key} accessibilityRole="button" accessibilityState={isFocused ? { selected: true } : {}} accessibilityLabel={options.tabBarAccessibilityLabel} testID={options.tabBarTestID} onPress={onPress} style={styles.tabItem} > {icon} <CustomText style={[styles.tabLabel, { color: isFocused ? '#007AFF' : '#8E8E93' }]}> {label} </CustomText> </TouchableOpacity> ); })} </View> ); }; const App = () => { return ( <ChatProvider> {/* Wrap NavigationContainer with ChatProvider */} <NavigationContainer> <Tab.Navigator initialRouteName="Figures" tabBar={(props) => <TabBar {...props} />} screenOptions={({ route }) => ({ headerShown: false, tabBarIcon: ({ focused, color, size }) => { let iconName = ''; if (route.name === 'Figures') { iconName = focused ? 'people' : 'people-outline'; } else if (route.name === 'Chats') { iconName = focused ? 'chatbubbles' : 'chatbubbles-outline'; } return <Ionicons name={iconName} size={size} color={color} />; }, })} > <Tab.Screen name="Figures" component={FiguresStack} options={{ tabBarLabel: 'Karakterler', }} /> <Tab.Screen name="Chats" component={ChatStack} options={{ tabBarLabel: 'Sohbetler', }} listeners={({ navigation, route }) => ({ tabPress: e => { // Prevent default behavior e.preventDefault(); // Reset the navigation stack to ChatList navigation.dispatch( CommonActions.reset({ index: 0, routes: [{ name: 'Chats', state: { routes: [{ name: 'ChatList' }] } }], }) ); }, })} /> </Tab.Navigator> </NavigationContainer> </ChatProvider> ); }; const styles = StyleSheet.create({ tabContainer: { flexDirection: 'row', backgroundColor: '#F8F8F8', borderTopWidth: 1, borderTopColor: '#E0E0E0', paddingBottom: Platform.OS === 'ios' ? 20 : 10, paddingTop: 10, }, tabItem: { flex: 1, alignItems: 'center', justifyContent: 'center', }, tabLabel: { fontSize: 12, marginTop: 3, fontFamily: 'Poppins_400Regular', }, }); export default App;
2.
src/context/ChatContext.tsxPlace this file separately in the
src/context/directory. This file manages the chat context, including adding, updating, and deleting chats.// src/context/ChatContext.tsx import React, { createContext, useState, useEffect, useCallback } from 'react'; import AsyncStorage from '@react-native-async-storage/async-storage'; import { Chat, Message } from '../types/types'; interface ChatWithLastMessage extends Chat { lastMessage?: string; lastMessageTimestamp?: number; } interface ChatContextProps { chats: ChatWithLastMessage[]; addChat: (chat: Chat, message: Message) => Promise<void>; updateChat: (chatId: string, message: Message) => Promise<void>; deleteChat: (chatId: string) => Promise<void>; deleteAllChats: () => Promise<void>; } export const ChatContext = createContext<ChatContextProps>({ chats: [], addChat: async () => {}, updateChat: async () => {}, deleteChat: async () => {}, deleteAllChats: async () => {}, }); export const ChatProvider: React.FC = ({ children }) => { const [chats, setChats] = useState<ChatWithLastMessage[]>([]); // Load chats from AsyncStorage on mount useEffect(() => { const loadChats = async () => { try { const chatsData = await AsyncStorage.getItem('chats'); const chatsList: Chat[] = chatsData ? JSON.parse(chatsData) : []; const chatsWithMessages: ChatWithLastMessage[] = await Promise.all( chatsList.map(async (chat) => { const messagesData = await AsyncStorage.getItem(`chat_${chat.id}_messages`); const messages: Message[] = messagesData ? JSON.parse(messagesData) : []; const lastMessage = messages[messages.length - 1]?.text || ''; const lastTimestamp = messages[messages.length - 1]?.timestamp || chat.createdAt; return { ...chat, lastMessage, lastMessageTimestamp: lastTimestamp, }; }) ); const sortedChats = chatsWithMessages.sort( (a, b) => (b.lastMessageTimestamp || 0) - (a.lastMessageTimestamp || 0) ); setChats(sortedChats); } catch (error) { console.error('Error loading chats:', error); } }; loadChats(); }, []); // Add a new chat const addChat = useCallback( async (chat: Chat, message: Message) => { try { const newChat: ChatWithLastMessage = { ...chat, lastMessage: message.text, lastMessageTimestamp: message.timestamp, }; const updatedChats = [...chats, newChat]; setChats(updatedChats); await AsyncStorage.setItem('chats', JSON.stringify(updatedChats)); await AsyncStorage.setItem(`chat_${chat.id}_messages`, JSON.stringify([message])); } catch (error) { console.error('Error adding chat:', error); } }, [chats] ); // Update an existing chat with a new message const updateChat = useCallback( async (chatId: string, message: Message) => { try { // Retrieve existing messages const messagesData = await AsyncStorage.getItem(`chat_${chatId}_messages`); const messages: Message[] = messagesData ? JSON.parse(messagesData) : []; const updatedMessages = [...messages, message]; await AsyncStorage.setItem(`chat_${chatId}_messages`, JSON.stringify(updatedMessages)); // Update chat's last message and timestamp setChats((prevChats) => { const updatedChats = prevChats .map((chat) => { if (chat.id === chatId) { return { ...chat, lastMessage: message.text, lastMessageTimestamp: message.timestamp, }; } return chat; }) .sort((a, b) => (b.lastMessageTimestamp || 0) - (a.lastMessageTimestamp || 0)); // Persist updated chats AsyncStorage.setItem('chats', JSON.stringify(updatedChats)).catch((err) => console.error('Error updating chats in AsyncStorage:', err) ); return updatedChats; }); } catch (error) { console.error('Error updating chat:', error); } }, [] ); // Delete a specific chat const deleteChat = useCallback( async (chatId: string) => { try { const updatedChats = chats.filter((chat) => chat.id !== chatId); setChats(updatedChats); await AsyncStorage.setItem('chats', JSON.stringify(updatedChats)); await AsyncStorage.removeItem(`chat_${chatId}_messages`); } catch (error) { console.error('Error deleting chat:', error); } }, [chats] ); // Delete all chats const deleteAllChats = useCallback(async () => { try { setChats([]); await AsyncStorage.removeItem('chats'); const keys = await AsyncStorage.getAllKeys(); const chatMessageKeys = keys.filter( (key) => key.startsWith('chat_') && key.endsWith('_messages') ); await AsyncStorage.multiRemove(chatMessageKeys); } catch (error) { console.error('Error deleting all chats:', error); } }, []); return ( <ChatContext.Provider value={{ chats, addChat, updateChat, deleteChat, deleteAllChats }}> {children} {/* Ensure only children are rendered */} </ChatContext.Provider> ); };
3. Additional Steps to Ensure Proper Functionality
-
Verify Other Components:
- Ensure that components like
HomeScreen,ChatListScreen,ChatScreen, andCustomTextare correctly implemented. - Specifically, make sure that no plain text is being rendered directly inside
Viewor other non-Textcomponents without wrapping them in<Text>components.
- Ensure that components like
-
Review
CustomTextComponent:- Ensure that the
CustomTextcomponent is a proper wrapper around React Native's<Text>component. - Example Implementation:
// src/components/CustomText.tsx import React from 'react'; import { Text, TextProps, StyleSheet } from 'react-native'; const CustomText: React.FC<TextProps> = ({ style, children, ...props }) => { return ( <Text style={[styles.text, style]} {...props}> {children} </Text> ); }; const styles = StyleSheet.create({ text: { fontFamily: 'Poppins_400Regular', }, }); export default CustomText;
- Ensure that the
-
Clear Metro Bundler Cache:
- Sometimes, cache issues can cause unexpected errors. Clear the cache by running:
or if you're using Expo:npx react-native start --reset-cacheexpo start -c
- Sometimes, cache issues can cause unexpected errors. Clear the cache by running:
-
Run Linting and Type Checking:
- Use TypeScript and ESLint to catch potential issues in your codebase.
- Ensure that all components return valid JSX and that there are no syntax errors.
-
Check Your Imports:
- Ensure that all imports are correctly pointing to the right files and that there are no circular dependencies.
-
Component Hierarchy:
- Double-check the component hierarchy to ensure that all components are properly nested and that there are no accidental renderings of plain text.
By following these steps and ensuring that
App.tsxandChatContext.tsxare properly separated, the error should be resolved. If the issue persists, consider inspecting other components in your application for similar issues or sharing more specific parts of your code for further assistance. -