React-Native with react-navigation navigate is not working - reactjs

react-navigation, navigation.navigate is not working in my component and does not show any error.
here is my navigator shopNavigation component:
import {createStackNavigator} from 'react-navigation-stack';
import {createAppContainer} from 'react-navigation';
import {Platform} from 'react-native';
import ProducOverviewScreen from '../screens/shop/ProductOverviewScreen';
import ProductDetailScreen from '../screens/shop/ProductDetailScreen';
import Colors from '../constants/Colors';
const ProductNavigator = createStackNavigator(
{
ProductOverview: ProducOverviewScreen,
ProductDetail: ProductDetailScreen
},
{
defaultNavigationOptions: {
headerStyle: {
backgroundColor: Platform.OS === 'android' ? Colors.primary: '',
},
headerTinColor: Platform.OS === 'android' ? 'white' : Colors.primary,
},
},
);
export default createAppContainer(ProductNavigator);
and this is the component i want to do the navigate function
ProductOverview
import React from 'react';
import {FlatList, Text} from 'react-native';
import {useSelector} from 'react-redux';
import ProductItem from '../../components/shop/ProductItem';
import { withNavigation, navigate } from 'react-navigation';
const ProductOverviewScreen = (props) => {
const products = useSelector(state => state.products.availableProducts);
return (
<FlatList
data={products}
keyExtractor={item => item.id}
renderItem={itemData => (
<ProductItem
image={itemData.item.imageUrl}
title={itemData.item.title}
price={itemData.item.price}
onViewDetail={()=> {
props.navigation.navigate('ProductDetail')
}}
onAddToCart={() => {}}
/>
)}
/>
);
};
ProductOverviewScreen.navigationOptions = {
title: 'All Products',
color: 'white',
headerTitleStyle: {
color: 'white',
},
};
export default ProductOverviewScreen;
the doc of react-navigation is not telling me much.
Thanks in advance

Related

I cannot read my state from another component (Redux)?

I'm having an issue about reading my state from another component. I use Redux Toolkit to store my state.
colorPick.js :
import { createSlice } from '#reduxjs/toolkit'
export const colorizerSlice = createSlice({
name: 'colorizer',
initialState: {
color: { nav: '#cecece',
bg: '#ebebeb' }
},
reducers: {
yellow: state => {
state.color = { nav: '#e1ce00',
bg: '#ffed27' }
},
red: state => {
state.color = { nav: '#e11300',
bg: '#ff3d27' }
},
green: state => {
state.color = { nav: '#00e104',
bg: '#4bff27' }
},
pink: state => {
state.color = { nav: '#e100ce',
bg: '#ff27fb' }
},
orange: state => {
state.color = { nav: '#e18b00',
bg: '#ff8527' }
},
// incrementByAmount: (state, action) => {
// state.value += action.payload
// }
}
})
// Action creators are generated for each case reducer function
export const { yellow,
red,
green,
pink,
orange, } = colorizerSlice.actions
export default colorizerSlice.reducer
store.js :
import { configureStore } from '#reduxjs/toolkit'
import colorizerReducer from './reducers/colorPick'
export default configureStore({
reducer: {
colorizer: colorizerReducer,
}
})
App.js :
import { StatusBar } from 'expo-status-bar';
import { useState, useEffect } from 'react';
import { Button, StyleSheet, Text, TextInput, View } from 'react-native';
import { NavigationContainer } from '#react-navigation/native';
import { createNativeStackNavigator } from '#react-navigation/native-stack';
import { Provider } from 'react-redux';
import Notes from './screens/Notes';
import ViewNote from './screens/ViewNote';
import EditNote from './screens/EditNote';
import AddNote from './screens/AddNote';
import store from './redux/store';
export default function App() {
const Stack = createNativeStackNavigator();
return (
<Provider store={store}>
<NavigationContainer>
<Stack.Navigator screenOptions={defaultOptions}>
<Stack.Screen name='Notes' component={Notes} options={notesOptions} />
<Stack.Screen name='ViewNote' component={ViewNote} options={viewNotesOptions} />
<Stack.Screen name='EditNote' component={EditNote} options={editNotesOptions} />
<Stack.Screen name='AddNote' component={AddNote} options={addNotesOptions} />
</Stack.Navigator>
</NavigationContainer>
</Provider>
);
}
ColorPalette.js : (I can read my state in this component)
import { StyleSheet, Text, View, Pressable } from 'react-native'
import React from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { green, red, yellow, orange, pink } from '../redux/reducers/colorPick'
const ColorPalette = () => {
const { color } = useSelector((state) => state.colorizer);
const dispatch = useDispatch();
console.log(color.nav);
return (
<View style={styles.paletteContainer}>
<Pressable style={[styles.color, {backgroundColor: '#ffed27'}]} android_ripple={{color: '#d9d9d9'}} onPress={() => dispatch(yellow())} />
<Pressable style={[styles.color, {backgroundColor: '#ff3d27'}]} android_ripple={{color: '#d9d9d9'}} onPress={() => dispatch(red())} />
<Pressable style={[styles.color, {backgroundColor: '#4bff27'}]} android_ripple={{color: '#d9d9d9'}} onPress={() => dispatch(green())} />
<Pressable style={[styles.color, {backgroundColor: '#ff27fb'}]} android_ripple={{color: '#d9d9d9'}} onPress={() => dispatch(pink())} />
<Pressable style={[styles.color, {backgroundColor: '#ff8527'}]} android_ripple={{color: '#d9d9d9'}} onPress={() => dispatch(orange())} />
<View style={{backgroundColor: color.nav, width:20}}></View>
<View style={{backgroundColor: color.bg, width:20}}></View>
</View>
)
}
NoteTile.js : (I cannot read in this component)
import { StyleSheet, Text, View, Pressable } from 'react-native'
import React from 'react'
import { useSelector } from 'react-redux'
const NoteTile = ({title, det, pressFunc}) => {
const { color } = useSelector((state) => state.colorizer);
// const color = useSelector((state) => state.colorizer.color);
return (
<View style={styles.tileContainer} >
<Pressable android_ripple={{color: '#cccccc'}}
style={styles.button}
onPress={pressFunc} >
<View style={[styles.innerContainer]} >
<Text style={styles.title} >{title}</Text>
<Text style={styles.details} >{det}</Text>
</View>
</Pressable>
</View>
)
}
export default NoteTile
const styles = StyleSheet.create({
tileContainer: {
flex: 1,
margin: 10,
height: 100,
maxHeight: 400,
borderRadius: 30,
elevation: 5,
overflow: 'hidden',
// backgroundColor: '#ffffff'
backgroundColor: color.bg,
}})
The error that I got is 'Can't find variable: color'
I wrapped my code with Provider.
And I use NoteTile.js in Notes Screen which is within the Provider.
try using it this way
<View style={[styles.tileContainer,{ backgroundColor:color.bg }]} >

Information not passing into component

In the code sample below, I am trying to show results.length but it does not show. The information is coming from the App.js screen, a filter function which I have pasted below. When I call <ResultsList reults={filtersResultsByPrice('$')} title='Cost Effective'/>, there may not be anything that is actually being sent into the ResultsList.js screen.
Here is the repo:
https://github.com/elaitman1/React-Native-Hooks-Project-1
ResultsList.js:
import React from 'react'
import {Text, View, StyleSheet} from 'react-native'
const ResultsList = ({title, results}) => {
if (results == null){
return null
}else{
return (
<View>
<Text style={styles.title}>{title}</Text>
<Text style={styles.title}>results: {results.length}</Text>
</View>
)
}
}
const styles = StyleSheet.create({
title:{
fontSize: 18,
fontWeight: 'bold'
}
})
export default ResultsList
App.js:
import { StyleSheet, Text, View } from 'react-native';
import SearchBar from './src/Components/SearchBar'
import React, {useState} from 'react'
import useResults from './src/hooks/useResults'
import ResultsList from './src/Components/ResultsList'
export default function App() {
const [term, setTerm] = useState('')
const [searchApi, results, errorMessage] = useResults()
const filtersResultsByPrice = (dollarSign) =>{
return results.filter((result) => {
return result.price === dollarSign
})
}
return (
<View>
<SearchBar
term={term}
onTermChange={setTerm}
onTermSubmit={() => searchApi(term)}
/>
{errorMessage ? <Text>{errorMessage}</Text> : null}
<Text>We have found {results.length} results</Text>
<ResultsList reults={filtersResultsByPrice('$')} title='Cost Effective'/>
<ResultsList reults={filtersResultsByPrice('$$')} title='Bit Pricier'/>
<ResultsList reults={filtersResultsByPrice('$$$')} title='Big Spender'/>
</View>
);
}
const styles = StyleSheet.create({
container: {
borderColor: 'black',
height: 40,
borderWidth: 3,
marginTop: 40
},
});

Why do i get "Could not find "store" in the context of "Connect(App)"" error when I connect my component to store

I have a component which I'm trying to connect with the global redux store. But when I do, I got an error which says that "Could not find "store" in the context of "Connect(App)"".
Here is my code:
App.js
import React from 'react';
import { StyleSheet, Text, View, TextInput, Button } from 'react-native';
import {connect} from 'react-redux'
function App() {
const geo = navigator.geolocation
if(!geo) {
} else {
geo.getCurrentPosition((response)=>{console.log(response)}, (response) => {console.log(response)})
}
return (
<View style={{padding: 40}}>
<View style={styles.form}>
<TextInput placeholder="Example text" style={styles.cityInput}/>
<Button title="Press ME!" onPress={(e)=> {console.log(e)}}/>
</View>
</View>
);
}
const styles = StyleSheet.create({
form: {
flexDirection: 'row',
justifyContent: 'space-between',
maxWidth: '100%'
},
cityInput: {
borderColor: 'black',
borderWidth: 2,
borderRadius: 5,
padding: 5,
width: '80%'
}
});
export default connect()(App)
index.js
import React from 'react'
import {AppRegistry} from 'react-native';
import App from './App'
import { name as appName } from './app.json'
import {Provider} from 'react-redux'
import configureStore from './src/reducers/store'
const store = configureStore();
const SunApp = () =>
<Provider store={store}>
<App />
</Provider>
AppRegistry.registerComponent(appName, () => SunApp)
store.js
import positionReducer from './positionReducer';
import sunReducer from './sunReducer';
import cityReducer from './cityReducer';
import {createStore, combineReducers} from 'redux';
const reducers = combineReducers({
positionReducer,
sunReducer,
cityReducer,
})
const configureStore = () => createStore(
reducers,
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
)
export default configureStore;
Here's the error
I can't figure out what I have to do to get rid of this error, so any feedback will be much appreciated
That error seems to come from your react native web entry point where the App is not wrapped in a <Provider (visible in the error message of the screenshot), not from the entry point you shared here.
So, indeed, the problem was in the entry point of my App. Because I was using managed workflow, the entry point of my application was registered to the App component, and my index.js file didn't make anything. So I managed to change my project structure a little bit so now my files looks like this:
App.js
import React from 'react';
import Main from './src/components/Main'
import {Provider} from 'react-redux'
import configureStore from './src/reducers/store'
const store = configureStore();
function App() {
return (
<Provider store={store}>
<Main />
</Provider>
);
}
export default App
Main.js
import React from 'react';
import { StyleSheet, Text, View, TextInput, Button } from 'react-native';
import {useEffect} from 'react'
import {connect, useSelector, useDispatch} from 'react-redux'
import axios from 'axios'
import {setPosition, setSun, setCity, setUndef, setInput} from '../actions'
function Main() {
const position = useSelector(state => state.positionReducer)
const sun = useSelector(state => state.sunReducer)
const city = useSelector(state => state.cityReducer)
const input = useSelector(state => state.inputReducer)
const dispatch = useDispatch();
function fail(error) {
alert(`Currently we can't get your location because: "${error.message}"`)
}
function success(response) {
dispatch(setPosition(response.coords));
}
function findCity(e) {
e.preventDefault()
dispatch(setCity(input))
axios.get('https://api.openweathermap.org/geo/1.0/direct', {
params: {
q: input,
limit: 1,
appid: 'a913b85241698a00b1014abe62a5ca0e'
}
})
.then(response => {
console.log(response);
if(response.data[0]) {
dispatch(setPosition(response.data[0]))
} else {
dispatch(setUndef())
}
})
}
useEffect(() => {
const geo = navigator.geolocation;
if(!geo) {
fail()
} else {
geo.getCurrentPosition(success, fail)
}
// eslint-disable-next-line
},[])
useEffect(() => {
if(position.lat && position.lat !== 'Not Found') {
axios.get('https://api.openweathermap.org/data/2.5/weather', {
params: {
lat: position.lat,
lon: position.lon,
appid: 'a913b85241698a00b1014abe62a5ca0e'
}
})
.then((response) => {
const sunriseTime = new Date(response.data.sys.sunrise * 1000)
const sunsetTime = new Date(response.data.sys.sunset * 1000)
const sun = {
sunrise: `${sunriseTime.getHours()}:${sunriseTime.getMinutes()}`,
sunset: `${sunsetTime.getHours()}:${sunsetTime.getMinutes()}`
}
dispatch(setSun(sun))
})
axios.get('https://api.openweathermap.org/geo/1.0/reverse', {
params: {
lat: position.lat,
lon: position.lon,
limit: 1,
appid: 'a913b85241698a00b1014abe62a5ca0e'
}
})
.then((response) => {
dispatch(setCity(response.data[0].name))
})
}
// eslint-disable-next-line
},[position])
return (
<View style={{padding: 40}}>
<View style={styles.form}>
<TextInput
placeholder="Example text"
style={styles.cityInput}
onChangeText={(e) => {dispatch(setInput(e))}}
onSubmitEditing={(e) => {dispatch(setInput(e.nativeEvent.text)); findCity(e)}}
/>
<Button title="Press ME!" onPress={findCity}/>
</View>
<View style={styles.info}>
<Text style={styles.infoText}>City: {city}</Text>
<Text style={styles.infoText}>Longitude :{position.lon}</Text>
<Text style={styles.infoText}>Latitude: {position.lat}</Text>
<Text style={styles.infoText}>Sunrise time: {sun.sunrise}</Text>
<Text style={styles.infoText}>Sunset time: {sun.sunset}</Text>
</View>
</View>
);
}
const styles = StyleSheet.create({
form: {
flexDirection: 'row',
justifyContent: 'space-between',
maxWidth: '100%'
},
cityInput: {
borderColor: 'black',
borderWidth: 2,
borderRadius: 5,
padding: 5,
width: '80%'
},
info: {
marginTop: 0,
marginBottom: 0,
marginLeft: 'auto',
marginRight: 'auto',
width: 'max-content'
},
infoText: {
fontSize: 20,
fontWeight: 700
}
});
export default connect()(Main)

React Native Navigation Open Draw From Header Button

I'm trying to open a navigation draw from a stack navigation header button. The header button is showing up fine but when I click the button I am getting
undefined is not an object (evaluating '_this.props.navigate')
I can't seem to find a solid example of how to do this or if its even possible with react navigation.
import React, { Component } from 'react';
import { createStackNavigator, NavigationActions } from 'react-navigation'
import Icon from 'react-native-vector-icons/MaterialCommunityIcons';
import { Draw } from './DrawNav.js'
export const RootStack = createStackNavigator (
{
DrawNav: {
screen: Draw,
navigationOptions: ({ navigation }) => ({
//Hide the shadow of the header
headerStyle: {
elevation:0,
shadowColor: 'transparent',
shadowRadius: 0,
shadowOffset: {
height: 0,
}
},
headerLeft: (
<View style={{marginLeft: 10}}>
<Icon
name="menu"
size={25}
color="#D4AF37"
onPress={() => this.props.navigation.openDrawer()}
/>
</View>
),
})
},
},
);
this.props is only used in a react class. I assume you're using react-navigation v2 then you should dispatch DrawerAction like below
import React, { Component } from 'react';
import { createStackNavigator, NavigationActions } from 'react-navigation'
import Icon from 'react-native-vector-icons/MaterialCommunityIcons';
import { DrawerActions } from 'react-navigation';
import { Draw } from './DrawNav.js'
export const RootStack = createStackNavigator (
{
DrawNav: {
screen: Draw,
navigationOptions: ({ navigation }) => ({
//Hide the shadow of the header
headerStyle: {
elevation:0,
shadowColor: 'transparent',
shadowRadius: 0,
shadowOffset: {
height: 0,
}
},
headerLeft: (
<View style={{marginLeft: 10}}>
<Icon
name="menu"
size={25}
color="#D4AF37"
onPress={() => navigation.dispatch(DrawerActions.openDrawer())}
/>
</View>
),
})
},
},
);

React-navigation contentComponent is not working

I am trying to customize drawer navigator in my app. I am using react-navigation. When first time I've inserted this code it showed just white screen and even navigation links were disappeared after making few things it showed this error screen.
Before that it showed just white screen inside drawer without my links. Here is the code.
App.js
import React from 'react';
import {StyleSheet, Text, View } from 'react-native';
import WelcomeScreen from './screens/WelcomeScreen';
import SigninScreen from './screens/SigninScreen';
import SignupScreen from './screens/SignupScreen';
import HomeScreen from './screens/HomeScreen';
import FoodScreen from './screens/FoodScreen';
import RestaurantsScreen from './screens/RestaurantsScreen';
import ProfileScreen from './screens/ProfileScreen';
import FavoritesScreen from './screens/FavoritesScreen';
import SettingsScreen from './screens/SettingsScreen';
import { TabNavigator, DrawerNavigator, StackNavigator,contentComponent } from 'react-navigation';
import {DrawerContent} from './components/DrawerContent'
export default class App extends React.Component {
render() {
const MainNavigator = TabNavigator({
welcome: { screen: WelcomeScreen },
signin: { screen: SigninScreen },
signup: { screen: SignupScreen },
main: {
screen: DrawerNavigator({
home: { screen: HomeScreen },
food: { screen: FoodScreen },
restaurants: { screen: RestaurantsScreen },
profile: {
screen: StackNavigator({
profilw: { screen: ProfileScreen },
settings: { screen: SettingsScreen }
})
}
},
{
contentComponent: props => <DrawerContent {...props} />,
}
)
}
},
);
return (
<MainNavigator />
);
}
}
DrawerContent.js
import React, { Component } from "react";
import { View, ScrollView,Button,Text } from "react-native";
class DrawerContent extends Component {
render() {
return (
<ScrollView style={styles.container}>
<View style={{ flex: 1 }}>
<Button transparent info onPress={() => { this.handlechange(); }}>
<Text style={{ fontSize: 16 }}>Change Email</Text>
</Button>
</View>
</ScrollView>
);
} }
const styles = {
container: {
flex: 1,
padding: 20,
backgroundColor: 'Green',
}, };
export default DrawerContent;
The button you are using is the button that should be imported from the
native base , as you are using the style property for that , or simply used this instead of that button code , replace it with below one
<Button onPress={() => { this.handlechange(); }} title="Learn More" color="#841584" />
Using this will help you with that
I think it's because contentComponent expects a class component, instead of using react-navigation, use react-navigation-drawer to import createDrawerNavigaor and DrawerNavigatorItems

Resources