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;
Related
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
StackRoutes.tsx Component (used in App.tsx)
export const StackRoutes = () => {
const Stack = createNativeStackNavigator()
return (
<NavigationContainer>
<Stack.Navigator initialRouteName={Path.introductionScreen}>
<Stack.Screen
name={Path.onBoardingChooseAliasScreen}
options={Options.onBoardingChooseAliasScreen}
component={OnBoardingChooseAlias}
/>
</Stack.Navigator>
</NavigationContainer>
)
}
Options.tsx component (being used in StackRoutes.tsx)
import React from 'react'
import { NativeStackNavigationOptions } from '#react-navigation/native-stack'
import { CustomBackButton } from './CustomBackButton'
const onBoardingChooseAliasScreen: NativeStackNavigationOptions = {
headerLeft: () => { return <CustomBackButton />}
}
export default {
onBoardingChooseAliasScreen,
}
CustomBackButton.tsx component (being used in Options.tsx)
import React from 'react'
import styled from 'styled-components/native'
import SVGimg from 'src/shared/images/greenMarker.svg'
export const CustomBackButton: React.FC<any> = ({ navigation }) => {
return (
<Wrapper onPress={() => navigation.goBack()}>
<SVGimg />
</Wrapper>
)
}
const Wrapper = styled.Pressable``
The CustomBackButton gets displayed as desired, but the goBack() function doesnt work. If i use default back button it works, so i know there is a stack to fall back on.
How do I make the goBack function work?
It seems like CustomBackButton does not have access to navigation
can you try with useNavigation hook
import React from 'react'
import styled from 'styled-components/native'
import SVGimg from 'src/shared/images/greenMarker.svg'
import { useNavigation } from '#react-navigation/native';
export const CustomBackButton: React.FC<any> = () => {
const navigation = useNavigation()
return (
<Wrapper onPress={() => navigation.goBack()}>
<SVGimg />
</Wrapper>
)
}
const Wrapper = styled.Pressable``
I have used createStackNavigator for Normal navigation and createMaterialTopTabNavigator for Tab navigation
Nested navigation is acting strangely. I have a StackNavigator in App.tsx that contains ProfileHome.tsx. The ProfileHome.tsx contains Tab navigations that have four screens. I wanted to navigate to the PastWorkDetail.tsx screen which is a part of the StackNavigator from PastWork.tsx (Tab)
Whenever I navigate from PastWork (Tab) to PastWorkDetail, the screen PastWorkDetail appears and automatically redirects to the previous screen, which is PastWork (Tab)
App.tsx
import { NavigationContainer } from "#react-navigation/native";
import { createStackNavigator } from "#react-navigation/stack";
import React, { useState } from "react";
import { SafeAreaProvider } from "react-native-safe-area-context";
import { RootStackParamList } from "./navigation/types";
import LoginHome from "./screens/login/LoginHome";
import SplashScreen from "./screens/login/SplashScreen";
import SocialMediaSelectPage from "./screens/preference/SocialMediaSelectPage";
import PastWorkDetail from "./screens/profile/PastWorkDetail";
import ProfileHome from "./screens/profile/ProfileHome";
const RootStack = createStackNavigator<RootStackParamList>();
const App = () => {
return (
<SafeAreaProvider>
<NavigationContainer>
<RootStack.Navigator
initialRouteName="LoginHome">
<RootStack.Screen name="LoginHome" component={LoginHome} />
<RootStack.Screen name="SocialMediaSelectPage" component={SocialMediaSelectPage}/>
<RootStack.Screen name="ProfileHome" component={ProfileHome} />
<RootStack.Screen name="PastWorkDetail" component={PastWorkDetail} />
<RootStack.Screen name="Test" component={Test} />
</RootStack.Navigator>
</NavigationContainer>
</SafeAreaProvider>
);
};
export default App;
ProfileHome.tsx
import { createMaterialTopTabNavigator } from "#react-navigation/material-top-tabs";
import React from "react";
import { View } from "react-native";
import HeaderProfile from "../../components/header/HeaderProfile";
import PastWork from "./PastWork";
import Preferences from "./Preferences";
import Profile from "./Profile";
import TopTabBar from "./shared/TopTabBar";
import Stats from "./Stats";
interface TabItem {
name: string;
component: React.ComponentType<any>;
}
const tabs: TabItem[] = [
{ name: "Profile", component: Profile },
{ name: "Stats", component: Stats },
{ name: "Preferences", component: Preferences },
{ name: "Pastwork", component: PastWork },
];
const ProfileHome = () => {
const Tab = createMaterialTopTabNavigator();
return (
<View style={styles.container}>
<Tab.Navigator backBehavior="history" nitialRouteName="Profile" tabBar={(props) => <TopTabBar {...props} />}>
{
// Populating tabs
tabs.map((item: TabItem, index: number) => {
return (
<Tab.Screenkey={index} name={item.name} component={item.component}
options={{
tabBarLabel: item.name,
}}
/>
);
})
}
</Tab.Navigator>
</View>
);
};
export default ProfileHome;
PastWork.tsx
import { useNavigation } from "#react-navigation/native";
import React from "react";
import { Image, ImageSourcePropType, StyleSheet, View } from "react-native";
const images = [
require("../../assets/images/pastWork1.jpeg"),
require("../../assets/images/pastWork2.png")
];
const PastWork = () => {
const navigation = useNavigation();
const onPress = () => {
navigation.navigate("PastWorkDetail");
};
return (
<View style={styles.container}>
<View style={{ width: Utils.getWidth(45) }}>
{
images.map((item, index) => {
return (
<ImageView key={index} source={item} onPress={onPress} />
);
})
}
</View>
</View>
);
};
export default PastWork;
PastWorkDetail.tsx
import React from "react";
import { StyleSheet, View } from "react-native";
import Header from "../../components/header/Header";
const PastWorkDetail = () => {
return (
<View style={styles.container}>
<Header name="Pastwork Info" />
</View>
);
};
export default PastWorkDetail;
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>
)};`
This is my first React Native project and I am stuck and need help. Following is my code. What I am trying to do is following.
Landing screen will have list of all projects and bottom tab menu.
Once someone clicks on project, it will open project details page.
App.Js
/**
* Sample React Native App
* https://github.com/facebook/react-native
*
* #format
* #flow strict-local
*/
import React from 'react';
import App from './src';
import { Provider as PaperProvider } from 'react-native-paper';
export default App;
src/navigations/index.js
import * as React from 'react';
import { Text, View, StyleSheet, FlatList, SafeAreaView } from 'react-native';
import { List, Button, TextInput, FAB, Avatar, Card, Title, Paragraph } from 'react-native-paper';
import { NavigationContainer } from '#react-navigation/native';
import { createBottomTabNavigator } from '#react-navigation/bottom-tabs';
import { createStackNavigator} from '#react-navigation/stack';
import ProjectList from '_scenes/projects';
import NewProject from '_scenes/projects/addproject';
import ProjectDetail from '_scenes/projects/projectdetails';
import Settings from '_scenes/settings';
const Tab = createBottomTabNavigator();
const Projects = ({ navigation }) => (
<ProjectList navigation={navigation} />
);
function SettingsScreen( { navigation} ) {
return (
<Settings />
);
}
export default function App() {
return (
<NavigationContainer>
<Tab.Navigator initialRouteName="HomeScreen">
<Tab.Screen name="Home" component={Projects} options={{ tabBarBadge: 3 }}/>
<Tab.Screen name="Settings" component={SettingsScreen} options={{ tabBarBadge: 2 }}/>
</Tab.Navigator>
</NavigationContainer>
);
}
src/scenes/projects/index.js
import React, { useEffect, useState } from 'react';
import { ActivityIndicator, FlatList, Text, View } from 'react-native';
import { Item, List, Button } from 'react-native-paper';
import { NavigationContainer } from '#react-navigation/native';
import { createBottomTabNavigator } from '#react-navigation/bottom-tabs';
import { createStackNavigator} from '#react-navigation/stack';
import NewProject from '_scenes/projects/addproject';
import ProjectDetail from './projectdetails';
ProjectList = ({ navisation }) => {
const [isLoading, setLoading] = useState(true);
const [data, setData] = useState([]);
useEffect(() => {
fetch('http://xxx.xxx.xxx.xxx/projects')
.then((response) => response.json())
.then((json) => setData(json))
.catch((error) => console.error(error))
.finally(() => setLoading(false));
}, []);
function Projects ( {navigation }) {
return (
<View style={{ flex: 1, padding: 24 }}>
<FlatList
data={data}
keyExtractor={({ id }, index) => id}
renderItem={renderProject}
/>
</View>
)
}
const renderProject = ({ navigation, item }) => (
<List.Item
title={item.title}
description={item.description}
onPress={() => navigation.navigate('ProjectDetails')}
/>
);
const AddProject = ({ navigation }) => (
<NewProject />
);
function ProjectDetails({navigation}) {
return (
<ProjectDetail />
);
}
function Chat({navigation}) {
return (
<View>
<Text>Chat</Text>
</View>
);
}
const Stack = createStackNavigator();
return (
<Stack.Navigator>
<Stack.Screen title="Home" name="Home" component={Projects} options={{headerShown: false}}/>
<Stack.Screen title="Add Project" name="AddProject" component={AddProject} />
<Stack.Screen title="Project Details" name="ProjectDetails" component={ProjectDetails} />
<Stack.Screen title="Chat" name="Chat" component={Chat} />
</Stack.Navigator>
);
};
export default ProjectList;
if you see "renderProject" I want to navigate to "ProjectDetails" when clicked. but I receive error 'TypeError: undefined is not an object (evaluating 'navigation.navigate')' let me know what is wrong?