react native moving data with useContext - react-native

this is a code from a tutorial about moving data with context the thing is the instructor is using 4.x navigator and since 4.x is not supported I tried to modify the navigation, but when I wrap the navigation with <BlogProvider></BlogProvider> nothing appears in the IndexScreen, as shown in picture 1.
and when i remove the <BlogProvider></BlogProvider> what I get is only this <Text>Index Screen</Text> and the Flatlist doesn't appear in the screen as shown in picture 2. .
and in both cases I get no error.
this is the App.js
import { StyleSheet, Text, View } from 'react-native';
import * as React from 'react';
import {NavigationContainer} from '#react-navigation/native';
import {createNativeStackNavigator} from '#react-navigation/native-stack';
import IndexScreen from './src/screens/IndexScreen';
import {BlogProvider} from './src/context/BlogContext';
const Stack = createNativeStackNavigator();
export default function App() {
return (
<BlogProvider>
<NavigationContainer>
<Stack.Navigator initialRouteName='IndexScreen'>
<Stack.Screen name='Blog' component={IndexScreen}/>
</Stack.Navigator>
</NavigationContainer>
</BlogProvider>
);
}
const styles = StyleSheet.create({});
this is the IndexScreen.js
import React, {useContext} from 'react';
import {Text, View, StyleSheet, FlatList} from 'react-native';
import BlogContext from '../context/BlogContext';
const IndexScreen = ()=>{
const blogPosts = useContext(BlogContext);
return (
<View>
<Text>Index Screen</Text>
<FlatList
data={blogPosts}
keyExtractor={(blogPost)=> blogPost.title}
renderItem={( { item } )=>{
<Text>{item.title}</Text>
}}
/>
</View>
);
};
const styles = StyleSheet.create({});
export default IndexScreen;
this is the BlogContextScreen.js
import React from 'react';
const BlogContext = React.createContext();
export const BlogProvider = ({ Children })=> {
const blogPosts = [{title: 'Blog Post #1'}, {title: 'Blog Post #2'}, {title: 'Blog Post #3'}];
return <BlogContext.Provider value={blogPosts}>
{Children}
</BlogContext.Provider>
};
export default BlogContext;
I will be glad for any support and again as you can see that I am still learning
Thank you in advance

The problem is not with the navigation. you have a syntax error in the BlogProvider component. the return block must be wrapped in parentheses:
import React from 'react';
const BlogContext = React.createContext();
export const BlogProvider = ({ children }) => {
const blogPosts = [
{ title: 'Blog Post #1' },
{ title: 'Blog Post #2' },
{ title: 'Blog Post #3' },
];
return (
<BlogContext.Provider value={blogPosts}>
{children}
</BlogContext.Provider>
);
};
export default BlogContext;

I found out that I forgot to add a return to the renderItem function
`const IndexScreen = ()=>{
const blogPosts = useContext(BlogContext);
return (
<View>
<Text>Index Screen</Text>
<FlatList
data={blogPosts}
keyExtractor={(blogPost)=> blogPost.title}
renderItem={( { item } )=>{
return <Text>{item.title}</Text>
}}
/>
</View>
)};`

Related

React native navigation not initialized yet

I'm learning react native but I'm having difficulty with navigation, it's returning the error that navigation has not been initialized yet.
I looked for some tutorials, I tried some other ways, I went to the react native navigation documentation and, incredible as it may seem, it's the same as in the documentation... not even the GPT chat haha ​​it didn't help me.
Can someone with experience in react native give me a light?
app.tsx:
import { NavigationContainer } from '#react-navigation/native';
import { createAppContainer } from 'react-navigation';
import StackNavigator from './app/index/navigator';
const AppContainer = createAppContainer(StackNavigator);
const App = () => {
return (
<NavigationContainer>
<AppContainer />
</NavigationContainer>
);
}
export default App;
navigator.tsx?
import { createStackNavigator } from 'react-navigation-stack';
import Index from '.';
import AddNewGrocery from '../components/addNewGrocery'
const StackNavigator = createStackNavigator({
home: { screen: Index, navigationOptions: { headerShown: false } },
addNewGrocery: { screen: AddNewGrocery, navigationOptions: { headerShown: false } },
});
export default StackNavigator;
index.tsx:
const Index = () => {
return (
<View style={styles.container}>
<Text style={styles.title}>Gestão de Compras</Text>
<LastFiveGrocery />
<MonthAverageSpend />
<TotalSpend />
<AddButton />
<StatusBar
translucent={false}
backgroundColor={'rgba(43, 43, 43, 1)'}
barStyle='light-content' />
</View>
);
}
AddButton.tsx:
import React from 'react';
import { StyleSheet, View, TouchableOpacity } from 'react-native';
import { Ionicons } from '#expo/vector-icons';
import { useNavigation } from '#react-navigation/native';
const AddButton = () => {
const navigation = useNavigation();
const handleAddButtonPress = () => {
navigation.navigate('addNewGrocery' as never);
}
return (
<TouchableOpacity style={styles.addButtonContainer} onPress={handleAddButtonPress}>
<View style={styles.addButton}>
<Ionicons name="ios-add" size={36} color="white" />
</View>
</TouchableOpacity>
);
}
I already tried to use it this way:
AddButton:
const { navigate } = useNavigation<StackNavigationProp<ParamListBase>>();
const handleAddButtonPress = () => {
navigate('addNewGrocery');
}
I've also tried using it this way:
navigator:
const StackNavigator = createAppContainer(createStackNavigator({
Home: { screen: Index },
addNewGrocery: AddNewGrocery,
}));
app.tsx:
import StackNavigator from './app/index/navigator';
const App = () => {
return (
<StackNavigator />
);
}
export default App;
You are using 2 different navigation library in simultaneously:
#react-navigation
react-navigation
Remove react-navigation and refactor the App.js file as below:
import { NavigationContainer } from '#react-navigation/native';
import StackNavigator from './app/index/navigator';
const App = () => {
return (
<NavigationContainer>
<StackNavigator />
</NavigationContainer>
);
}
export default App
StackNavigator should be implemented as per documentation -
https://reactnavigation.org/docs/stack-navigator/#api-definition

Error when calling a component react native

I want to create a component like this to check if the user idle or not.
import React, {useState, useEffect, useRef} from 'react';
import {View, PanResponder, StyleSheet} from 'react-native';
const ScreenConponent = ({...props}) => {
console.tron.log(props);
const timerId = useRef(false);
const [timeForInactivityInSecond, setTimeForInactivityInSecond] =
useState(3600);
useEffect(() => {
resetInactivityTimeout();
}, []);
const panResponder = React.useRef(
PanResponder.create({
onStartShouldSetPanResponderCapture: () => {
console.tron.log('user starts touch');
resetInactivityTimeout();
},
}),
).current;
const resetInactivityTimeout = () => {
clearTimeout(timerId.current);
timerId.current = setTimeout(() => {
console.tron.log('user idle');
}, timeForInactivityInSecond * 1000);
};
return (
<View style={styles.container} {...panResponder.panHandlers}>
{props.children}
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
},
});
export default ScreenConponent;
and this is how i call the component
import React, {useState, useEffect} from 'react';
import {View, Text} from 'react-native';
import Screen from '../../components/Screen';
export default function App() {
return (
<Screen>
<View> <Text> Test </Text> </View>
</Screen>
);
}
But when i tried to call the component, i got an error like this error when run the app
anyone have an idea what's wrong with the code? because i can use this method in react (web)
this is the navigation code
import React from 'react';
import {createStackNavigator} from '#react-navigation/stack';
// import {createBottomTabNavigator} from '#react-navigation/bottom-tabs';
import {NavigationContainer} from '#react-navigation/native';
import ScheduleScreen from '../pages/Schedule';
const Stack = createStackNavigator();
/** Main route */
const MainNavigator = () => {
return (
<Stack.Screen
name="Schedule"
component={ScheduleScreen}
options={{
header: () => null,
}}
/>
</Stack.Navigator>
);
};
const Root = createStackNavigator();
const RootNavigator = () => {
return (
<NavigationContainer>
<Root.Navigator>
<Root.Screen
name="Main"
component={MainNavigator}
options={{header: () => null}}
/>
</Root.Navigator>
</NavigationContainer>
);
};
export default RootNavigator;

react native navigation error "navigate is undefined"

I am creating a react native application and I have problem when I want to navigate between screens it gives error as " Cannot read property 'navigate' of Undefined " . I want when I press gear icon it must navigate to settings part . I couldn't clearly see where did I mistake .
settings button touchable opacity
import React from 'react';
import {createStackNavigator} from 'react-navigation-stack';
import { createAppContainer} from 'react-navigation';
import PS from '../screens/PS';
import SPC from '../screens/SPC';
import TFA from '../screens/2FA';
import Login from '../screens/Login';
import Settings from '../screens/settings';
const screens = {
Login: {
screen: Login,
navigationOptions: {
header: null,
}
},
TFA:{
screen: TFA
},
PS: {
screen: PS,
navigationOptions: {
header: null,
}
},
SPC: {
screen: SPC
},
Settings: {
screen: Settings
}
}
const HomeStack = createStackNavigator(screens);
export default createAppContainer(HomeStack);
import React, {useState}from 'react';
import SettingsButton from './SettingsButton';
import ConnectionIcon from './Connectionİcon';
import { View, Image, StyleSheet } from 'react-native';
const Header = () => {
return (
<View style={styles.header}>
<View style={styles.headerp1}></View>
<View style={styles.headerp2}><Image
source={require('../assets/images/monitor.png')}
/></View>
<View style={styles.headerp3}>
<SettingsButton />
<ConnectionIcon />
</View>
</View>
)
}
export default Header;
// const styles here
import React from 'react';
import { Image, TouchableOpacity, StyleSheet } from 'react-native';
const SettingsButton = ({ navigation }) => {
return (
<TouchableOpacity
style={styles.headerp3v2}
onPress={() => navigation.navigate('Settings')}
>
<Image style={styles.reddot}
source={require('../assets/images/gear.png')}
/>
</TouchableOpacity>
)
}
export default SettingsButton;
// const stlyes codes here
header file is here
import { Image, StyleSheet, Button, View, Text, SafeAreaView, StatusBar } from 'react-native';
import Footer from '../components/Footer';
import Header from '../components/Header';
import PV from '../components/PV';
export default function PS() {
return (
<View style={styles.container}>
<StatusBar hidden />
<Header />
<View><Text style={styles.text}>All Persons</Text></View>
<PV />
<Footer/>
</View>
);
}```
You don't pass navigation prop into SettingsButton
You can try use useNavigation hook https://reactnavigation.org/docs/use-navigation/ for get navigation object into SettingsButton
import React from 'react';
import { Image, TouchableOpacity, StyleSheet } from 'react-native';
import { useNavigation } from '#react-navigation/native'; // <-- new code
const SettingsButton = () => {
const navigation = useNavigation(); // <-- new code
return (
<TouchableOpacity
style={styles.headerp3v2}
onPress={() => navigation.navigate('Settings')}
>
<Image style={styles.reddot}
source={require('../assets/images/gear.png')}
/>
</TouchableOpacity>
)
}
export default SettingsButton;

passing a prop from index into header component

I'm following a udemy tutorial on react-native.
I'm trying to pass a prop from my index.js into my header.js. The header should say, "Albums". But is is always showing up blank.
If I remove {props.headerText} from header.js and replace it with
"Albums"
then it works. But I'm trying to make the component reusable per the tutorial instructions.
note: I'm using Create React Native App and this is on an android emulator.
App.js
import React from 'react';
import { View } from 'react-native';
import Header from './src/components/header';
export default class App extends React.Component {
render() {
return (
<Header />
);
}
}
index.js
import React from 'react';
import { Text, AppRegistry } from 'react-native';
import Header from './src/components/header';
const App = () => (
<Header headerText={'Albums'} />
);
AppRegistry.registerComponent('albums', () => App);
header.js
import React from 'react';
import { Text, View } from 'react-native';
const Header = (props) => {
const { textStyle, viewStyle } = styles;
return (
<View style={viewStyle}>
<Text style={textStyle}>{props.headerText}</Text>
</View>
);
};
const styles = {
viewStyle: {
justifyContent: 'center'
},
headerStyle: {
fontSize: 20
}
};
export default Header;
Am I missing anything? I've been over and over each file line by line and I can't find any issues.
Thanks!
I would suggest you
const Header = ({props}) => {
const { textStyle, viewStyle } = styles;
return (
<View style={viewStyle}>
<Text style={textStyle}>{props.headerText}</Text>
</View>
);
};
And to pass props ;
const App = () => (
<Header props={someProps} />
);

Disable console log in react navigation

I'm using react navigation for my app development. When i run log-android, it keeps logging something like this.
Navigation Dispatch: Action: {...}, New State: {...}
which is from createNavigationContainer.js line 150.
I've run through github and document said it could be done by by setting onNavigationStateChange={null} on a top-level navigator.
How can i achieve this by setting onNavigationStateChange={null} and where should i set it?
I've try to set like below, but it the page will not be able to redirect to other page.
export default () => {
<App onNavigationStateChange={null} />
}
Below are my app.js code
import React, { Component } from 'react';
import { AppRegistry, StyleSheet, Text, View } from 'react-native';
import { StackNavigator,DrawerNavigator } from 'react-navigation';
import DrawerContent from './components/drawer/drawerContent.js';
import News from './components/news/home.js';
const drawNavigation = DrawerNavigator(
{
Home : {
screen : News ,
navigationOptions : {
header : null
}
}
},
{
contentComponent: props => <DrawerContent {...props} />
}
)
const StackNavigation = StackNavigator({
Home : { screen : drawNavigation,
navigationOptions: {
header: null
}
}
});
export default StackNavigation;
This is my drawerContent.js
import React, {Component} from 'react'
import {View,Text, StyleSheet,
TouchableNativeFeedback,
TouchableOpacity,
TouchableHighlight
} from 'react-native'
import { DrawerItems, DrawerView } from 'react-navigation';
import Icon from 'react-native-vector-icons/Octicons';
import MaterialIcons from 'react-native-vector-icons/MaterialIcons';
class DrawerContent extends Component {
constructor(props){
super(props);
console.log('DrawerContent|testtttttt');
}
render(){
return (
<View style={styles.container}>
<Text>Hi darren</Text>
<TouchableOpacity style={{ marginBottom:5 }} onPress={() => this.props.navigation.navigate('RegistrationScreen') } >
<View style={styles.nonIconButton}>
<Text style={{ color: 'black',fontSize: 13 }} >Sign Up</Text>
</View>
</TouchableOpacity>
<Text>Hi darren</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
});
export default DrawerContent;
First, make sure you are using the latest release of react-navigation as the comment noting that the fix was committed is fairly recent.
Based on your code example, to disable logging for all navigation state changes, you would want to replace this code:
export default StackNavigation;
with:
export default () => (
<StackNavigation onNavigationStateChange={null} />
);
as StackNavigation appears to be your root navigator.
React navigation is great, but this logging is really bad. Solution
const AppNavigator = StackNavigator(SomeAppRouteConfigs);
class App extends React.Component {
render() {
return (
<AppNavigator onNavigationStateChange={null} />
);
}
}