Call setstate inside NavigationOptions React native - reactjs

I'm trying to change value of state inside navigationOptions.
my navigation options
static navigationOptions = ({ navigation }) => {
const { params = {} } = navigation.state;
// alert(params.searchText);
return {
headerLeft: (params.searchText) ? <View
style={{
flexDirection:
'row', justifyContent: 'center'
}}>
<TouchableOpacity
onPress={()=> {
// navigation.navigate('home');
alert('Coming soon ');
}}>
<Image style={{ marginLeft: 20, height: 20, width: 20, resizeMode: "contain" }}
source={require('../assets/header_icons/three_logo.png')}
/>
</TouchableOpacity>
</View> :
<View style={{
flexDirection:
'row', justifyContent:
'center'
}}>
<TouchableOpacity
onPress={()=> {
this.setState({
loadUrl: "card.html#!/customer-dashboard?userType=Authenticated",
showWeb:true,
});
}}>
<Image style={{ marginLeft: 20, height: 20, width: 20, resizeMode: "contain" }}
source={require('../assets/header_icons/icon_arrow_left.png')}
/>
</TouchableOpacity>
</View>,
}
}
It's throwing this.setState is not an function
Please let me know how to achieve this. How can we change value of state from static navigationOptions

You can use redux store.
store.js
import ReduxThunk from "redux-thunk";
import { createStore, combineReducers, applyMiddleware } from "redux";
import authReducer from "./reducers/auth";
import dashboardReducer from "./reducers/dashboard";
import profileReducer from "./reducers/profile";
const rootReducer = combineReducers({
auth: authReducer,
dashboard: dashboardReducer,
profile: profileReducer
});
export default createStore(rootReducer, applyMiddleware(ReduxThunk));
Dashboard.js
import React, { Component } from "react";
import {
View,
Text,
Image,
StyleSheet,
Dimensions,
TouchableOpacity,
ScrollView,
ActivityIndicator
} from "react-native";
import OrientationScreen from "./OrientationScreen";
import { connect, useDispatch } from "react-redux";
import store from "../store/store";
class Dashboard extends Component {
render() {
const dashboard = this.props;
if (dashboard.orientation) {
return <OrientationScreen />;
} else {
return (
<View style={styles.screen}>
{this.props.dashboard.loading && (
<View style={styles.loading}>
<ActivityIndicator color={Colors.blueButton} size="large" />
</View>
)}
<Text>You are logged in</Text>
</View>
);
}
}
_openOrientation() {
store.dispatch(dashboardActions.openOrientation());
}
static navigationOptions = ({ navigation, navigationOptions }) => {
const params = navigation.state.params || {};
return {
headerTitle: "Dashboard",
headerRight: (
<HeaderButtons HeaderButtonComponent={HeaderButton}>
<Item
Title="Orientation"
iconName="ios-help-circle-outline"
iconSize={30}
onPress={params.openOrientation}
/>
<Item
Title="Menu"
iconName="ios-menu"
iconSize={30}
onPress={() => navigation.toggleDrawer()}
/>
</HeaderButtons>
)
};
}
}
const mapStateToProps = state => {
const { auth, dashboard } = state;
return { auth, dashboard };
};
export default connect(mapStateToProps)(Dashboard);
actions/dashboard.js
const openOrientation = () => {
return dispatch => {
return dispatch({
type: "OPEN_ORIENTATION"
});
};
};
export default {
openOrientation
};
reducers/dashboard.js
const initialState = {
loading: false,
error: null,
orientation: false,
UserData: null
};
export default (state = initialState, action) => {
switch (action.type) {
case "OPEN_ORIENTATION":
return {
...state,
orientation: true
};
case "CLOSE_ORIENTATION":
return {
...state,
orientation: false
};
case "LOADING":
return {
...state,
error: null,
loading: true
};
default:
return state;
}
};
SwiperFlatList.js
import React, { PureComponent } from "react";
import { Text, Dimensions, Image, StyleSheet, View } from "react-native";
import SwiperFlatList from "react-native-swiper-flatlist";
export default class OrientationScreen extends PureComponent {
constructor(props) {
super(props);
this.state = {
images: [
require("../assets/images/SLIDE-1.jpg"),
require("../assets/images/SLIDE-2.jpg"),
require("../assets/images/SLIDE-3.jpg"),
require("../assets/images/SLIDE-4.jpg"),
require("../assets/images/SLIDE-5.jpg"),
require("../assets/images/SLIDE-6.jpg"),
require("../assets/images/SLIDE-7.jpg"),
require("../assets/images/SLIDE-8.jpg"),
require("../assets/images/SLIDE-9.jpg"),
require("../assets/images/SLIDE-10.jpg"),
require("../assets/images/SLIDE-11.jpg"),
require("../assets/images/SLIDE-12.jpg"),
require("../assets/images/SLIDE-13.jpg"),
require("../assets/images/SLIDE-14.jpg"),
require("../assets/images/SLIDE-15.jpg"),
require("../assets/images/SLIDE-16.jpg"),
require("../assets/images/SLIDE-17.jpg"),
require("../assets/images/SLIDE-18.jpg"),
require("../assets/images/SLIDE-19.jpg"),
require("../assets/images/SLIDE-20.jpg"),
require("../assets/images/SLIDE-21.jpg"),
require("../assets/images/SLIDE-22.jpg"),
require("../assets/images/SLIDE-23.jpg"),
require("../assets/images/SLIDE-24.jpg"),
require("../assets/images/SLIDE-25.jpg"),
require("../assets/images/SLIDE-26.jpg"),
require("../assets/images/SLIDE-27.jpg"),
require("../assets/images/SLIDE-28.jpg"),
require("../assets/images/SLIDE-29.jpg"),
require("../assets/images/SLIDE-30.jpg"),
require("../assets/images/SLIDE-31.jpg"),
require("../assets/images/SLIDE-32.jpg")
]
};
}
render() {
const orientationBody = this.state.images.map((item, i) => {
return (
<View key={i} style={styles.child}>
<Image
source={item}
resizeMode="contain"
style={styles.imageprofile}
/>
</View>
);
});
return (
<View style={styles.container}>
<SwiperFlatList
index={0}
removeClippedSubviews={false}
showPagination={false}
>
{orientationBody}
</SwiperFlatList>
</View>
);
}
}
export const { width, height } = Dimensions.get("window");
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "white"
},
child: {
height: height * 0.8,
width,
justifyContent: "center"
},
text: {
fontSize: width * 0.5,
textAlign: "center"
},
imageprofile: {
width: "100%"
}
});

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 }]} >

Getting a Reference Error when starting my react native app

I am getting a reference Error message: can't find variable:error, i'm not able to figure out where I have written this variable in code. Someone help!!
This is my App.js (Starting point)
import React from 'react';
import Main from './components/MainComponent';
import { Provider } from 'react-redux';
import { ConfigureStore } from './redux/configureStore';
const store = ConfigureStore();
export default class App extends React.Component {
render() {
return (
<Provider store={store}>
<Main />
</Provider>
);
}
}
ActionTypes.js (This file represents different Actions which can be dispatched)
export const DISHES_LOADING = 'DISHES_LOADING';
export const ADD_DISHES = 'ADD_DISHES';
export const DISHES_FAILED = 'DISHES_FAILED';
export const ADD_COMMENTS = 'ADD_COMMENTS';
export const COMMENTS_FAILED = 'COMMENTS_FAILED';
export const PROMOS_LOADING = 'PROMOS_LOADING';
export const ADD_PROMOS = 'ADD_PROMOS';
export const PROMOS_FAILED = 'PROMOS_FAILED';
export const LEADERS_LOADING = 'LEADERS_LOADING';
export const ADD_LEADERS = 'ADD_LEADERS';
export const LEADERS_FAILED = 'LEADERS_FAILED';
ActionCreators.js (This file fetches data from a fake Rest api and performs the necessary computations dispatches the data and action accordingly )
import {createStore, combineReducers, applyMiddleware} from 'redux';
import thunk from 'redux-thunk';
import logger from 'redux-logger';
import { dishes } from './dishes';
import { comments } from './comments';
import { promotions } from './promotions';
import { leaders } from './leaders';
export const ConfigureStore = () => {
const store = createStore(
combineReducers({
dishes,
comments,
promotions,
leaders
}),
applyMiddleware(thunk, logger)
);
return store;
}
AboutComponent.js (This is one of my component)
import React, {Component} from 'react';
import { Text, ScrollView } from 'react-native';
import { Card } from 'react-native-elements';
import { FlatList } from 'react-native';
import { ListItem } from 'react-native-elements';
import { connect } from 'react-redux';
import { baseUrl } from '../shared/baseUrl';
import { Loading } from './LoadingComponent';
const mapStateToProps = state => {
return {
leaders: state.leaders
}
}
function History() {
return(
<Card title="Our History">
<Text style={{margin: 10}}>
Started in 2010, Ristorante con Fusion quickly established itself as a culinary icon par excellence in Hong Kong. With its unique brand of world fusion cuisine that can be found nowhere else, it enjoys patronage from the A-list clientele in Hong Kong. Featuring four of the best three-star Michelin chefs in the world, you never know what will arrive on your plate the next time you visit us.{"\n\n"}
The restaurant traces its humble beginnings to The Frying Pan, a successful chain started by our CEO, Mr. Peter Pan, that featured for the first time the world's best cuisines in a pan.
</Text>
</Card>
);
}
function RenderLeaders(props) {
const leaders = props.leaders;
const renderLeaderItems = ({item, index}) => {
return (
<ListItem
key={index}
title={item.name}
subtitle={item.description}
hideChevron={true}
leftAvatar={{source: {uri: baseUrl + item.image}}}
/>
);
};
return (
<Card title='Comments' >
<FlatList
data={leaders}
renderItem={renderLeaderItems}
keyExtractor={item => item.id.toString()}
/>
</Card>
);
}
class About extends Component {
static navigationOptions = {
title: 'About Us'
};
render(){
if (this.props.leaders.isLoading) {
return(
<ScrollView>
<History />
<Card
title='Corporate Leadership'>
<Loading />
</Card>
</ScrollView>
);
}
else if (this.props.leaders.errMess) {
return(
<ScrollView>
<History />
<Card
title='Corporate Leadership'>
<Text>{this.props.leaders.errMess}</Text>
</Card>
</ScrollView>
);
}
else{
return (
<ScrollView>
<History/>
<RenderLeaders leaders={this.props.leaders.leaders} />
</ScrollView>
)
}
}
}
export default connect(mapStateToProps)(About);
MainComponent.js (The file which controls the side drawer and navigation)
import React, {Component } from 'react';
import Menu from './MenuComponent';
import DishDetail from './DishdetailComponent';
import { View, Platform, Image, StyleSheet, ScrollView, Text } from 'react-native';
import {createStackNavigator} from 'react-navigation-stack';
import { createAppContainer, SafeAreaView } from 'react-navigation';
import { createDrawerNavigator, DrawerItems } from 'react-navigation-drawer';
import Home from './HomeComponent';
import Contact from './ContactComponent';
import About from './AboutComponent';
import {Icon} from 'react-native-elements';
import { connect } from 'react-redux';
import { fetchDishes, fetchComments, fetchPromos, fetchLeaders } from '../redux/ActionCreators';
const mapStateToProps = state => {
return {
}
}
const mapDispatchToProps = dispatch => ({
fetchDishes: () => dispatch(fetchDishes()),
fetchComments: () => dispatch(fetchComments()),
fetchPromos: () => dispatch(fetchPromos()),
fetchLeaders: () => dispatch(fetchLeaders()),
})
const MenuNavigator = createStackNavigator({
Menu:{screen:Menu,
navigationOptions:({navigation}) => ({
headerLeft: <Icon name='menu' size={24} color='white'
onPress={()=>navigation.toggleDrawer()}
/>
})},
DishDetail: { screen: DishDetail }
}, {
initialRouteName: 'Menu',
navigationOptions: {
headerStyle: {
backgroundColor: "#512DA8"
},
headerTintColor: '#fff',
headerTitleStyle: {
color: "#fff"
}
}
});
const HomeNavigator = createStackNavigator({
Home: { screen: Home }
}, {
navigationOptions: ({ navigation }) => ({
headerStyle: {
backgroundColor: "#512DA8"
},
headerTitleStyle: {
color: "#fff"
},
headerTintColor: "#fff",
headerLeft: <Icon name='menu' size={24} color='white'
onPress={()=>navigation.toggleDrawer()}
/>
})
});
const AboutNavigator = createStackNavigator({
Home: { screen: About }
}, {
navigationOptions: ({ navigation }) => ({
headerStyle: {
backgroundColor: "#512DA8"
},
headerTitleStyle: {
color: "#fff"
},
headerTintColor: "#fff",
headerLeft: <Icon name='menu' size={24} color='white'
onPress={()=>navigation.toggleDrawer()}
/>
})
});
const ContactNavigator = createStackNavigator({
Home: { screen: Contact }
}, {
navigationOptions: ({ navigation }) => ({
headerStyle: {
backgroundColor: "#512DA8"
},
headerTitleStyle: {
color: "#fff"
},
headerTintColor: "#fff",
headerLeft: <Icon name='menu' size={24} color='white'
onPress={()=>navigation.toggleDrawer()}
/>
})
});
const CustomDrawerContentComponent = (props) => (
<ScrollView>
<SafeAreaView style={styles.container} forceInset={{ top: 'always', horizontal: 'never' }}>
<View style={styles.drawerHeader}>
<View style={{flex:1}}>
<Image source={require('./images/logo.png')} style={styles.drawerImage} />
</View>
<View style={{flex: 2}}>
<Text style={styles.drawerHeaderText}>Ristorante Con Fusion</Text>
</View>
</View>
<DrawerItems {...props} />
</SafeAreaView>
</ScrollView>
);
const MainNavigator = createDrawerNavigator({
Home:
{ screen: HomeNavigator,
navigationOptions: {
title: 'Home',
drawerLabel: 'Home',
drawerIcon: ({tintColor}) => (
<Icon
name='home'
type='font-awesome'
size={24}
color={tintColor}
/>
)
}
},
About:
{ screen: AboutNavigator,
navigationOptions: {
title: 'About Us',
drawerLabel: 'About Us',
drawerIcon: ({tintColor}) => (
<Icon
name='info-circle'
type='font-awesome'
size={24}
color={tintColor}
/>
)
}
},
Menu:
{ screen: MenuNavigator,
navigationOptions: {
title: 'Menu',
drawerLabel: 'Menu',
drawerIcon: ({tintColor}) => (
<Icon
name='list'
type='font-awesome'
size={24}
color={tintColor}
/>
)
},
},
Contact:{
screen:ContactNavigator,
navigationOptions: {
title: 'Contact Us',
drawerLabel: 'Contact Us',
drawerIcon: ({tintColor}) => (
<Icon
name='address-card'
type='font-awesome'
size={22}
color={tintColor}
/>
)
}
}
}, {
drawerBackgroundColor: '#D1C4E9',
contentComponent: CustomDrawerContentComponent
});
const App = createAppContainer(MainNavigator);
class Main extends Component {
componentDidMount() {
this.props.fetchDishes();
this.props.fetchComments();
this.props.fetchPromos();
this.props.fetchLeaders();
}
onDishSelect(dishId) {
this.setState({selectedDish: dishId})
}
render() {
return (
<View style={{flex:1, paddingTop: Platform.OS === 'ios' ? 0 : Expo.Constants.statusBarHeight }}>
<App />
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
drawerHeader: {
backgroundColor: '#512DA8',
height: 140,
alignItems: 'center',
justifyContent: 'center',
flex: 1,
flexDirection: 'row'
},
drawerHeaderText: {
color: 'white',
fontSize: 24,
fontWeight: 'bold'
},
drawerImage: {
margin: 10,
width: 80,
height: 60
}
});
export default connect(mapStateToProps, mapDispatchToProps)(Main);

How to set the state from a button inside static navigationoption react-native?

I want to click the TouchableOpacity and set the state true so that will open. I am getting error. and how to align the button in center at the header? alignSelf is not working.
`
import React, {Component} from 'react';
import {
StyleSheet,
SafeAreaView,
View,
TouchableOpacity,
Text,
} from 'react-native';
import Menu from '../../src/components/menubar';
export default class SearchPage extends Component {
constructor(props) {
super(props);
this.state = {isMenubarDisplayed: false};
}
static navigationOptions = {
headerTitle: () => {
return (
<TouchableOpacity
onPress={()=> this.setState({isMenubarDisplayed: true})}>
<Icon name="search" size={20} color="#000" />
</TouchableOpacity>
);
},
headerTitleStyle: {
alignSelf: 'center',
flex: 1,
},
};
render() {
return (
<SafeAreaView style={styles.container}>
{this.state.isMenubarDisplayed ? (
<Menu />
) : null}
</SafeAreaView>
);
}
}`
You need to try this, expo-snack .
This is my below code for search.js ,
import * as React from 'react';
import { Text, View, StyleSheet,TouchableOpacity } from 'react-native';
import Constants from 'expo-constants';
import Menu from './menu';
import Icon from 'react-native-vector-icons/FontAwesome';
export default class Search extends React.Component {
constructor(props){
super(props);
this.state={
isMenubarDisplayed: false,
}
}
static navigationOptions = ({ navigation }) => {
return {
headerTitle: () => {
return (
<TouchableOpacity onPress={navigation.getParam('toggleMenu')}>
<Icon name="search" size={20} color="#000" />
</TouchableOpacity>
);
},
};
};
toggleMenu = () => {
this.setState({ isMenubarDisplayed: !this.state.isMenubarDisplayed})
}
renderMenu = () => (
<Menu />
)
componentDidMount(){
this.props.navigation.setParams({
toggleMenu: this.toggleMenu
});
}
render() {
return (
<View style={styles.container}>
{this.state.isMenubarDisplayed?this.renderMenu():<View></View>}
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
paddingTop: Constants.statusBarHeight,
backgroundColor: '#ecf0f1',
padding: 8,
},
});
Hope it helps. feel free for doubts.
This is all you need https://reactnavigation.org/docs/en/header-buttons.html#header-interaction-with-its-screen-component
static navigationOptions = ({ navigation }) => {
return {
headerTitle: () => {
return (
<View style={{ flex: 1, alignItems: 'center' }}>
<TouchableOpacity onPress={navigation.getParam('toggleMenu')}>
<Icon name="search" size={20} color="#000" />
</TouchableOpacity>
</View>
);
},
};
};
componentDidMount() {
this.props.navigation.setParams({ toggleMenu: this.toggleMenu });
}
toggleMenu = () => {
this.setState({isMenubarDisplayed: true});
}

cant find variable props

I am trying to show the detail view when user taps on one of the list item. When the user taps on the listitem, I get an error saying Undefined is not an object
evaluating 'this.props.services.ser. Below is the screen shot of the error:
My list item page code is below:
import React, { Component } from 'react';
import { Text, View, StyleSheet, ListView } from 'react-native';
import { Provider, connect } from 'react-redux';
import { createStore } from 'redux'
import reducers from '../reducers/ServiceReducer';
import ServiceItem from './ServiceItem';
import Icon from 'react-native-vector-icons/EvilIcons';
import ServiceDetail from './ServiceDetail';
const styles = StyleSheet.create({
container: {
flex: 1,
width: 353,
flexWrap: 'wrap',
paddingTop: 20,
paddingLeft: 20,
},
});
const store = createStore(reducers);
class AutoCompActivity extends Component {
renderInitialView() {
const ds = new ListView.DataSource({
rowHasChanged: (r1, r2) => r1 !== r2,
});
this.dataSource = ds.cloneWithRows(this.props.services);
if (this.props.detailView === true) {
return (
<ServiceDetail />
);
} else {
return (
<ListView
enableEmptySections={true}
dataSource={this.dataSource}
renderRow={(rowData) =>
<ServiceItem services={rowData} />
}
/>
);
}
}
render() {
return (
<View style={styles.container}>
{this.renderInitialView()}
</View>
);
}
}
const mapStateToProps = state => {
return {
services: state.services,
detailView: state.detailView,
};
};
const ConnectedAutoCompActivity = connect(mapStateToProps)(AutoCompActivity);
const app1 = () => (
<Provider store={store}>
<ConnectedAutoCompActivity />
</Provider>
)
export default app1;
Each item that I display to the user is defined in js class serviceItem.js. Below is the code for serviceItem.js. I put the entire code inside TouchableWithoutFeedback. This is when I am getting an error when user taps on one of the listItem. I looked at this code several times, but could not figure out where I am doing wrong
import React from 'react';
import { Text, View, StyleSheet, Image, TouchableWithoutFeedback } from 'react-native';
import { connect } from 'react-redux';
import { getTheme } from 'react-native-material-kit';
import Icon from 'react-native-vector-icons/EvilIcons';
import * as actions from '../actions';
const theme = getTheme();
const styles = StyleSheet.create({
card: {
marginTop: 20,
},
title: {
top: 20,
left: 80,
fontSize: 24,
},
image: {
height: 100,
},
action: {
backgroundColor: 'black',
color: 'white',
},
icon: {
position: 'absolute',
top: 15,
left: 0,
color: 'white',
backgroundColor: 'rgba(255,255,255,0)',
},
});
const ServiceItem = (props) => {
return (
<TouchableWithoutFeedback
onPress={() => props.selectServices(props.services)}
>
<View style={[theme.cardStyle, styles.card]}>
<Text >{props.services.ser} </Text>
</View>
</TouchableWithoutFeedback>
);
};
const mapStateToProps = state => {
return {
selectServices: state.selectServices,
services: state.services
};
};
export default connect(mapStateToProps, actions)(ServiceItem);
When the user taps on each listitem. I am calling the class ServiceDetail.js. Below is the code for serviceDetail.js class:
/**
* Sample React Native App
* https://github.com/facebook/react-native
* #flow
*/
import React, { Component } from 'react';
import { Text, View, StyleSheet, Image, ScrollView, TouchableOpacity, Linking } from 'react-native';
import { connect } from 'react-redux';
import { getTheme } from 'react-native-material-kit';
import EvilIcon from 'react-native-vector-icons/EvilIcons';
import MaterialIcon from 'react-native-vector-icons/MaterialIcons';
import SimpleIcon from 'react-native-vector-icons/SimpleLineIcons';
import * as actions from '../actions';
const theme = getTheme();
const styles = StyleSheet.create({
card: {
marginTop: 10,
paddingBottom: 20,
marginBottom: 20,
borderColor: 'lightgrey',
borderWidth: 0.5,
},
title1: {
top: 10,
left: 80,
fontSize: 24,
},
title2: {
top: 35,
left: 82,
fontSize: 18,
},
image: {
flex: 0,
height: 100,
width: 333,
backgroundColor: 'transparent',
justifyContent: 'center',
alignItems: 'center',
},
closeIcon: {
position: 'absolute',
top: 5,
left: 295,
color: 'rgba(233,166,154,0.8)',
backgroundColor: 'rgba(255,255,255,0)',
},
icon: {
position: 'absolute',
top: 15,
left: 0,
color: 'white',
backgroundColor: 'rgba(255,255,255,0)',
},
textArea: {
flexDirection: 'row',
paddingLeft: 20,
paddingTop: 10,
width: 260,
},
textIcons: {
color: '#26a69a',
},
actionArea: {
paddingTop: 10,
flexDirection: 'row',
justifyContent: 'space-around',
alignItems: 'center',
},
});
class ServiceDetail extends Component {
handleClick = (link) => {
Linking.canOpenURL(link).then(suppported => {
if (supported) {
Linking.openURL(link);
} else {
console.log('Don\'t know how to open URI: ' + link);
}
});
};
render() {
return (
<ScrollView showsVerticalScrollIndicator={false}>
<View style={[theme.cardStyle, styles.card]}>
<Image
source={require('../images/background.jpg')}
style={[theme.cardImageStyle, styles.image]}
/>
<EvilIcon name={'user'} size={100} style={styles.icon}/>
<SimpleIcon name={'close'} size={30} style={styles.closeIcon}
onPress={() => this.props.noneSelected()} />
<Text style={[theme.cardTitleStyle, styles.title1]}>{this.props.services.ser}</Text>
<Text style={[theme.cardTitleStyle, styles.title2]}>from {this.props.services.Location}</Text>
<Text style={[theme.cardTitleStyle, styles.title2]}>from {this.props.services.SecondLoc}</Text>
<View style={styles.textArea}>
<MaterialIcon name={'phone'} size={40} style={styles.textIcons}/>
<Text style={theme.cardContentStyle}>{this.props.services.Phone}</Text>
</View>
<View style={styles.textArea}>
<MaterialIcon name={'email'} size={40} style={styles.textIcons}/>
<Text style={theme.cardContentStyle}>{this.props.services.email}</Text>
</View>
<View style={styles.actionArea}>
<Text>Call</Text>
<Text>Email</Text>
</View>
</View>
</ScrollView>
);
}
}
const mapStateToProps = state => {
return {
service: state.serviceSelected,
};
};
export default connect(mapStateToProps, actions)(ServiceDetail);
My index.js class has the following code under actions folder:
export const selectServices = (serviceId) => {
return {
type: 'SELECTED_SERVICE',
payload: serviceId,
};
};
export const noneSelected = () => {
return {
type: 'NONE_SELECTED',
};
};
My serviceReducer has the following code:
import services from './services.json';
const initialState = {
services,
detailView: false,
serviceSelected: null,
};
export default (state = initialState, action) => {
switch (action.type) {
case 'SELECTED_SERVICE':
return {
...state,
detailView: true,
serviceSelected: action.payload
}
case 'NONE_SELECTED':
return {
...state,
detailView: false,
serviceSelected: null,
}
default:
return state;
}
}
I am developing this application on windows machine on android emulator. I know I am missing something. I looked at each and every line, but could not figure out what am I doing wrong. I am new to react native and trying to follow the example to make this app. I tried to debug the application using chrome, but keep getting an error that could not connect to remote debugging.
any help will be highly appreciated.
I see you pass props and use it to your const ServiceItem. You need to use mapStateToProps also then pass to your connect at serviceItem.js.
const mapStateToProps = state => {
return {
selectServices: state.selectServices,
services: state.services
};
};
export default connect(mapStateToProps, actions)(ServiceItem);
Your ServiceDetail.js also should be:
const mapStateToProps = state => {
return {
services: state.services
};
};
export default connect(mapStateToProps, actions)(ServiceDetail);
Your ServiceItem component is just a presentational component, in my opinion, it need not to be connected to redux store, instead, pass the data and event hook from parent to ServiceItem component and that will work just fine. That will solve your props problem as well.
Point made by "DennisFrea" still holds good. i am just suggesting another of achieving the same thing.

React Native Navigation with React Native Admob About

I created a 3 page application with React native navigation. Admob ads are on the 3rd page. I want to try the same ad code on all three screens. If there is any idea in this matter, please share. Thank you.
For better understanding I give the following expo code.
import React, { Component } from 'react';
import {
WebView,
AppRegistry,
StyleSheet,
Text,
View,
Button,
Alert
} from 'react-native';
import { StackNavigator } from 'react-navigation';
import ListComponent from './ListComponent';
class App extends Component {
static navigationOptions = {
title: 'App',
};
OpenSecondActivityFunction = () => {
this.props.navigation.navigate('Second');
};
render() {
return (
<View style={styles.container}>
<Button
onPress={this.OpenSecondActivityFunction}
title="Open Second Activity"
/>
</View>
);
}
}
class SecondActivity extends Component {
static navigationOptions = {
title: 'SecondActivity',
};
OpenThirdActivityFunction = data => {
this.props.navigation.navigate('Third');
};
render() {
return (
<View style={{ flex: 1 }}>
<ListComponent
OpenThirdActivityFunction={this.OpenThirdActivityFunction}
/>
</View>
);
}
}
class ThirdActivity extends Component {
static navigationOptions = {
title: 'ThirdSecondActivity',
};
render() {
return (
<View style={{ flex: 1 }}>
<Text>3</Text>
</View>
);
}
}
const ActivityProject = StackNavigator({
First: { screen: App },
Second: { screen: SecondActivity },
Third: { screen: ThirdActivity },
});
export default ActivityProject;
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
}
});
Listcomponent.js
import React, { Component } from 'react';
import {
AppRegistry,
View,
Text,
FlatList,
ActivityIndicator,
} from 'react-native';
import { List, ListItem, SearchBar } from 'react-native-elements';
class ListComponents extends Component {
constructor(props) {
super(props);
this.state = {
loading: false,
data: [],
page: 1,
seed: 1,
error: null,
refreshing: false,
};
}
renderSeparator = () => {
return (
<View
style={{
height: 1,
width: '98%',
backgroundColor: '#CED0CE',
marginLeft: '2%',
}}
/>
);
};
renderHeader = () => {
return <SearchBar placeholder="Type Here..." lightTheme round />;
};
renderFooter = () => {
if (!this.state.loading) return null;
return (
<View
style={{
paddingVertical: 20,
borderTopWidth: 1,
borderColor: '#CED0CE',
}}>
<ActivityIndicator animating size="large" />
</View>
);
};
render() {
return (
<List containerStyle={{ borderTopWidth: 0, borderBottomWidth: 0 }}>
<FlatList
data={[{ name: 1, coders: 2 }]}
renderItem={({ item }) => (
<ListItem
roundAvatar
title={`${item.name}`}
subtitle={item.coders}
containerStyle={{ borderBottomWidth: 0 }}
onPress={() => this.props.OpenThirdActivityFunction(item.coders)}
/>
)}
keyExtractor={item => item.coders}
ItemSeparatorComponent={this.renderSeparator}
ListHeaderComponent={this.renderHeader}
ListFooterComponent={this.renderFooter}
/>
</List>
);
}
}
export default ListComponents;

Resources