how can I send props to other file? - reactjs

How can I send props to another file?
I have a component file. And there is an array where data are pushed. If the user click ok, then I want the array to another file.
example:
sizeComponent.js
import React from 'react';
import { StyleSheet, View, Text, TouchableOpacity, FlatList, Dimensions } from 'react-native';
import pure from 'recompose/pure';
const width = Dimensions.get('window').width;
const height = Dimensions.get('window').height;
const AboveSize = ({ data, onPress }) => {
return (
<View style={{marginTop: 10}}>
<Text style={{color: '#333', fontSize: 16}}>Bekleidungsgröße</Text>
<View style={{flexDirection: 'row', flexWrap: 'wrap'}}>
<FlatList
data={data}
keyExtractor={item => item.key}
horizontal
getItemLayout={(data, index) => {
return {
index,
length: 200,
offset: height * index
}
}}
showsHorizontalScrollIndicator={false}
renderItem={({ item }) => {
return (
<TouchableOpacity onPress={onPress} style={{borderWidth: 1, borderColor: '#ccc', justifyContent: 'center', alignItems: 'center', borderRadius: 8, height: 77, width: 77, margin: 12, marginLeft: 0, backgroundColor: data.includes(item.size) ? 'red' : 'blue'}}>
<Text style={{color: data.includes(item.size) ? '#fff' : '#333', fontSize: 20}}>{item.size}</Text>
</TouchableOpacity>
)
}}
/>
</View>
</View>
)
};
export default pure(AboveSize);
Main.js
import SizeComponent from 'sizeComponent';
/* Size from Mock Data */
const productData = [
{
item: {
id: 1,
name:"Calvin Klein Bag",
price:"29.99€",
size: [
{
key: "1",
size: "XS"
},
{
key: "2",
size: "S",
},
{
key: "3",
size: "M"
},
{
key: "4",
size: "L"
},
{
key: "5",
size: "XL"
},
{
key: "6",
size: "XXL"
},
{
key: "7",
size: "XXXL"
}
],
}
}];
const [productSize, setProductSize] = useState([]);
...
<SizeComponent data={productData} onPress={() => console.log('I want here the data from the component file which was selected')}

In the sizeComponent.js change the onPress method to the following code:
<TouchableOpacity onPress={()=>onPress(item)}
so when the onPress is called the selected item will be passed to the callback method which you can access like this
<SizeComponent data={productData} onPress={(item) => {//the seleteced item will be accessible here })

React Native applications are built using components that manage state internally.
To globalize your state there is a state management libraries like Redux exist to solve this issue. Redux provides a central location for all the states of an application where each component can access the values stored in the state.
reducer.js
import { combineReducers } from "redux";
const INITIAL_STATE = { table:[] };
const reducers = (state = INITIAL_STATE, action) => {
switch (action.type) {
case "PUSH_TABLE":
state.table.push(action.value)
return { ...state, table: state.table };
default:
return state;
}
};
export default combineReducers({ reducers: reducers });
action.js
export const pushTable = (title) => ({
type: "PUSH_TABLE",
value: title
});
app.js
import React from "react";
import ListScreen from "./src/ListScreen";
import ModalScreen from "./src/ModalScreen";
import { NavigationContainer } from "#react-navigation/native";
import { createStackNavigator } from "#react-navigation/stack";
import { Provider } from "react-redux";
import { createStore } from "redux";
import reducer from "./src/reducer";
const store = createStore(reducer);
const Stack = createStackNavigator();
function MainStackNavigator() {
return (
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen name="List" component={ListScreen} />
<Stack.Screen name="Modal" component={ModalScreen} />
</Stack.Navigator>
</NavigationContainer>
);
}
export default function App() {
return (
<>
<Provider store={store}>
<MainStackNavigator />
</Provider>
</>
);
}
Table.js
import React from "react";
import { Button } from "react-native";
import { connect } from "react-redux";
import { bindActionCreators } from "redux";
import { pushTable } from "./action";
class Table extends React.Component {
render() {
return (
<>
<Button
title={"PUSH TABLE"}
onPress={() => this.props.pushTable("NICE") }
/>
{this.props.reducers.table.map((cel, index) => (
<Text>{cel} {index}</Text>
))}
</>
);
}
}
const mdtp = (dispatch) => bindActionCreators( { pushTable, }, dispatch );
const mtp = (state) => {
const { reducers } = state;
return { reducers };
};
export default connect(mtp, mdtp)(Table);

Related

Bug that I can't understand and fix in React Native

To put in context I am building an app as an exercise in a course to program in react native and we are learning Redux
For me everything is fine but I have doubts in two parts in the index of the scene where the application is seen in this case welcome / index.js there is a line that is for 'useSelector' and another is in the reduce of recipe that if the data is well linked because it throws me an error.
"ERROR TypeError: undefined is not an object (evaluating 'store.getState')"
I share the different components of the redux.
Everything is in a store folder and everything is modulated
store/reduce
store/reduce/index.js
import { combineReducers, createStore } from "redux";
import { recipesReducer } from "./reducer";
const rootReducer = combineReducers({
recipes: recipesReducer
});
export default createStore(rootReducer);
store/reducer/recipes.reducer.js
import {recipeTypes} from '../types';
import {recipes} from '../../data';
const { SELECT_RECIPE } = recipeTypes;
const initialState = {
recipes: recipes,
selectedRecipe: null
}
const recipesReducer = (state = initialState, action) => {
switch(action.type) {
case SELECT_RECIPE:
const indexRecipe = state.recipes.findIndex(
(recipe) => recipe.id === action.recipeId
);
if(indexRecipe === -1) return state;
return {
...state,
selectedRecipe: state.recipes[indexRecipe]
}
default:
return state;
}
}
export default recipesReducer;
store/reduce/index.js
export {default as recipesReducer} from './recipes.reducer';
store/types/index.js
export * from './recipes.types';
store/types/recipes.type.js
export const recipeTypes = {
SELECT_RECIPE: 'SELECT_RECIPE',
}
store/action/recipes.action.js
import { recipeTypes } from '../types';
const { SELECT_RECIPE } = recipeTypes;
export const selectRecipe = (id) => {
return {
type: SELECT_RECIPE,
recipeId: id,
};
}
store/action/index.js
export * from './repice.action';
welcome/index
import {Button, CardsRecipes, MenuAlt, Pickers, TT} from '../../components';
import { FlatList, StyleSheet, Text, View } from 'react-native';
import React, { useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import Color from '../../constants/colors';
import { recipe } from '../../data';
import { selectRecipe } from '../../store/action';
const Welcome= ({navigation, route}) => {
const dispatch = useDispatch();
const recipe = useSelector(state => state.recipe.recipe);
const onSelected = (item) => {
dispatch(selectRecipe(item.id));
navigation.navigate('Recipe');
}
const renderItem = ({item}) => <CardsRecipes item={item} onSelected={onSelected(item)} />
return (
<View style={styles.container}>
<MenuAlt title = {'Recetas'} />
<View style={styles.textContainer}>
<Text style= {styles.text}>Bienvenido a la App de Recetas de Cocina</Text>
</View>
<View style = {styles.buttonContainer}>
</View>
<FlatList
data= {recipe}
renderItem = {renderItem}
keyExtractor = {item => item.id}
/>
</View >
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: Color.primary,
color: Color.letter,
fontFamily: 'Lato-Regular',
},
textContainer: {
alignItems: 'center',
justifyContent: 'center',
},
text: {
color: Color.letter,
fontSize: 20,
fontWeight: 'bold',
marginTop: 10,
marginBottom: 10,
},
buttonContainer: {
width: '100%',
alignItems: 'center',
marginTop: 10,
marginBottom: 10,
height: 33,
},
});
export default Welcome;
app.js
import {ActivityIndicator, StyleSheet, View} from 'react-native';
import React, { useState } from 'react';
import AppNavigator from './navigation';
import Color from './constants/colors';
import { Provider } from 'react-redux';
import { StatusBar } from 'expo-status-bar';
import { store } from './store';
import { useFonts } from 'expo-font';
export default function App() {
//useState
const [selected, setSelected] = useState(false);
const [order, setOrder] = useState([]);
//funciones
const [loaded] = useFonts({
'Lato-Regular': require('./assets/fonts/Lato-Regular.ttf'),
'Lato-Bold': require('./assets/fonts/Lato-Bold.ttf'),
'Lato-Light': require('./assets/fonts/Lato-Light.ttf'),
'Lato-Italic': require('./assets/fonts/Lato-Italic.ttf'),
'Lato-Black': require('./assets/fonts/Lato-Black.ttf'),
});
if(!loaded) {
return (
<View style={styles.containerLoader}>
<ActivityIndicator size="large" color={Color.letter} />
</View>
)
}
const onSelectedEnlarge = ( select, order ) => {
setOrder(order)
setSelected(select);
};
/*
let content = <Super onSelectedEnlarge={onSelectedEnlarge} object = {order}/>;
if (!selected) {
content = <Super onSelectedEnlarge={onSelectedEnlarge} object = {order}/>;
}
else
{
content = <ListSuper onSelectedEnlarge={onSelectedEnlarge} object = {order}/>;
}
*/
return (
<Provider store={store}>
<AppNavigator/>
</Provider>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: Color.primary,
color: Color.letter,
fontFamily: 'Lato-Regular',
},
});
thanks for your help

How can I display an array of images after get the urls React Native

Im trying to display a preview of the picked images after pick them, im using this library import { AssetsSelector } from 'expo-images-picker';
This is the code to pick the image:
import React, { useMemo } from 'react';
import { Text, View, StyleSheet, SafeAreaView, Alert } from 'react-native';
import { AssetsSelector } from 'expo-images-picker';
import { Ionicons } from '#expo/vector-icons';
import { AntDesign } from '#expo/vector-icons';
import { SafeAreaProvider } from 'react-native-safe-area-context';
import { MediaType } from 'expo-media-library';
import { useNavigation } from '#react-navigation/core';
export default function App() {
const navigation = useNavigation();
const onSuccess = (data: any) => {
const filteredUri = data.filter(({ uri }) => uri).map(({ uri }) => uri);
navigation.navigate('AddProductScreen',
{
filteredUri: filteredUri,
});
};
const widgetErrors = useMemo(
() => ({
errorTextColor: 'black',
errorMessages: {
hasErrorWithPermissions: 'Please Allow media gallery permissions.',
hasErrorWithLoading: 'There was error while loading images.',
hasErrorWithResizing: 'There was error while loading images.',
hasNoAssets: 'No images found.',
},
}),
[]
);
const widgetSettings = useMemo(
() => ({
getImageMetaData: false,
initialLoad: 100,
assetsType: [MediaType.photo, MediaType.video],
minSelection: 1,
maxSelection: 3,
portraitCols: 4,
landscapeCols: 4,
}),
[]
);
const widgetResize = useMemo(
() => ({
width: 50,
compress: 0.7,
base64: false,
saveTo: 'jpeg',
}),
[]
);
const _textStyle = {
color: 'white',
};
const _buttonStyle = {
backgroundColor: 'orange',
borderRadius: 5,
};
const widgetNavigator = useMemo(
() => ({
Texts: {
finish: 'finish',
back: 'back',
selected: 'selected',
},
midTextColor: 'black',
minSelection: 1,
buttonTextStyle: _textStyle,
buttonStyle: _buttonStyle,
onBack: () => {navigation.goBack()},
onSuccess: (e: any) => onSuccess(e),
}),
[]
);
const widgetStyles = useMemo(
() => ({
margin: 2,
bgColor: 'white',
spinnerColor: 'blue',
widgetWidth: 99,
videoIcon: {
Component: Ionicons,
iconName: 'ios-videocam',
color: 'tomato',
size: 20,
},
selectedIcon: {
Component: Ionicons,
iconName: 'ios-checkmark-circle-outline',
color: 'white',
bg: '#0eb14970',
size: 26,
},
}),
[]
);
return (
<SafeAreaProvider>
<SafeAreaView style={styles.container}>
<View style={styles.container}>
<AssetsSelector
Settings={widgetSettings}
Errors={widgetErrors}
Styles={widgetStyles}
Navigator={widgetNavigator}
/>
</View>
</SafeAreaView>
</SafeAreaProvider>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
});
This is the code where I want o display the images, im using react navigation props to get the array:
const showPickedImages = ({ route, navigations }) => {
const navigation = useNavigation();
var filteredUri = route.params?.filteredUri;
return(
<View>
//Here I want to show the preview of the picked images
<View/>
)}
You can use Flatlist or ScrollView for this.
<Flatlist
ListEmptyComponent={
<Text>Loading...</Text>} // show loading text until you get the data
data={filteredUri}
renderItem={(uri)=>
<Image source={{uri}} style={{widht:100, height:100}} />
}
/>

How to pass data to different screens

I need to pass data from one screen to anothre, an main screen loads and then loads the data from a mock api, it sets the state with providerData, then navigation gets created. I want to be able to use the data i got in the ProviderDetailScreen.js in ProviderOverview.js
Here is ProviderDetailsScreen.js
import React from 'react';
import {StatusBar, View} from 'react-native';
import ProviderOverview from './ProviderOverview';
import ProviderServicesList from './ProviderServicesList';
import NavigationbarHeaderWithExpandedImage from '../components/NavigationbarHeaderWithExpandedImage';
import TopTabbarComponent from '../components/TopTabbarComponent';
import mockApi from '../mockApi';
const ProviderDetailScreen = ({navigation, route}) => {
const [providerData, setProviderData] = React.useState({});
const [loading, setLoading] = React.useState(false);
//navigation setup
React.useLayoutEffect(() => {
navigation.setOptions({
header: ({scene, previous}) => {
return (
<NavigationbarHeaderWithExpandedImage
scene={scene}
previous={previous}
navigation={navigation}
backgroundImage={providerData?.profile?.backgroundImage}
/>
);
},
});
}, [navigation, providerData]);
//get results from API
const getServices = React.useCallback(async () => {
try {
setLoading(true);
const res = await mockApi.get('/Provider/Profile');
if (res.ok && res.body.data) {
// use this data in overview and service list
setLoading(false);
setProviderData(res.body.data);
} else {
throw new Error('Unable to retrieve profile');
}
} catch (error) {
console.log(error);
}
}, []);
React.useEffect(() => {
console.warn('here');
getServices();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return (
<>
<StatusBar barStyle="light-content" />
<TopTabbarComponent
items={[
{
title: 'Overview',
component: ProviderOverview,
},
{
title: 'Services',
component: ProviderServicesList,
},
{
title: 'Reviews',
component: View,
},
]}
/>
</>
);
};
export default ProviderDetailScreen;
Here is The ToTabbarComponent.js that created a tab for each item in providerdetailsscreen
import React from 'react';
import {StyleSheet} from 'react-native';
import {createMaterialTopTabNavigator} from '#react-navigation/material-top-tabs';
import {PRIMARY, WHITE, INACTIVE_TINT_COLOR, ACCENT} from '../lib/colors';
import fonts from '../lib/fonts';
const Tab = createMaterialTopTabNavigator();
const TopTabbarComponent = ({items}) => {
const tabs = () => {
let tabs = [];
// loop to create tabs
for (const [index, item] of items.entries()) {
tabs.push(
<Tab.Screen
name={item.title}
title={item.title}
component={item.component}
key={index}
/>,
);
}
return tabs;
};
return (
<Tab.Navigator
tabBarOptions={{
activeTintColor: WHITE,
labelStyle: [styles.labelStyle, fonts.medium],
inactiveTintColor: INACTIVE_TINT_COLOR,
style: styles.style,
indicatorStyle: styles.indicatorStyle,
}}>
{tabs()}
</Tab.Navigator>
);
};
const styles = StyleSheet.create({
tabBarOptions: {},
labelStyle: {
fontSize: 14,
},
indicatorStyle: {
backgroundColor: ACCENT,
height: 2,
},
style: {
backgroundColor: PRIMARY,
},
});
export default TopTabbarComponent;
Here is the ProviderOverview.js where i want to use that data that gets set in ProviderDetailsScreen.js
//WANT TO USE DATA HERE
import React from 'react';
import {StyleSheet, View, ScrollView, Text} from 'react-native';
import MediumText from '../components/MediumText';
const ProviderOverview = ({navigation}) => {
return (
<ScrollView style={styles.container}>
<View>
<MediumText onPress={() => navigation.push('PROVIDER_MESSAGE')}>
Send a message
</MediumText>
</View>
<View></View>
</ScrollView>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
},
});
export default ProviderOverview;
I am still learning: Things i have tried:
In providerDetailsscreen i tried to set providerdata for each item, i tried setting a test var with some string to see if i can get it in ProviderOverview. But providerOverview only has Navigation prop.
Thanks in advance.
Try this way
ProviderDetailsScreen.js
<TopTabbarComponent
items={[
{
title: 'Overview',
component: ProviderOverview,
providerData: providerData, // set providerData to ProviderOverview
},
{
title: 'Services',
component: ProviderServicesList,
},
{
title: 'Reviews',
component: View,
},
]}
/>
TopTabbarComponent
// loop to create tabs
for (const [index, item] of items.entries()) {
const CompView = item.component;
const providerData = item.providerData || {};
tabs.push(
<Tab.Screen name={item.title} title={item.title} key={index}>
{(props) => <CompView {...props} {...providerData} />}
</Tab.Screen>
);
}
You can use navigation props
this.props.navigation.navigate('MyData', {data: data,});
https://reactnavigation.org/docs/navigation-prop/#navigate
Or add redux to your project https://redux.js.org/introduction/getting-started

Mapping over data after fetching nested objects

Hello guys so i have component homescreen which i am fetching data inside and, the data i am getting contains some objects that has arrays inside, so i want to push all that arrays and data inside my state otherDetails key .
the data i am getting looks like this
{
id: 5,
url: "http://www.tvmaze.com/shows/5/true-detective",
name: "True Detective",
type: "Scripted",
language: "English",
genres: [
"Drama",
"Crime",
"Thriller"
],
status: "To Be Determined",
runtime: 60,
premiered: "2014-01-12",
officialSite: "http://www.hbo.com/true-detective",
schedule: {
time: "21:00",
days: [
"Sunday"
]
},
rating: {
average: 8.2
},
weight: 97,
network: {
id: 8,
name: "HBO",
country: {
name: "United States",
code: "US",
timezone: "America/New_York"
}
},
webChannel: null,
externals: {
tvrage: 31369,
thetvdb: 270633,
imdb: "tt2356777"
},
image: {
medium: "http://static.tvmaze.com/uploads/images/medium_portrait/178/445621.jpg",
original: "http://static.tvmaze.com/uploads/images/original_untouched/178/445621.jpg"
},
summary: "<p>Touch darkness and darkness touches you back. <b>True Detective</b> centers on troubled cops and the investigations that drive them to the edge. Each season features a new cast and a new case.</p>",
now what i am trying to do inside home screen i have my state with the object key otherDetails which i am trying to get genres language network schedule and summary so i am not sure what is happening wrong
this is my HomeScreen.js
import React, {Component} from 'react';
const axios = require('axios');
import Card from '../Components/Card/card';
import {
View,
Text,
Button,
Image,
ScrollView,
ActivityIndicator,
} from 'react-native';
import DetailsScreen from './detailsScreen';
import DetailedCard from '../Components/DetailedCard/DetailedCard';
export default class HomeScreen extends React.Component {
state = {
title: [],
image: [],
rating: [],
otherDetails:[{
genres:[],
schedule:[],
language:'',
network:[],
summary:'',
} ],
isLoading: true,
};
componentDidMount() {
this.getData();
}
getData = () => {
const requestUrls = Array.from({length: 9}).map(
(_, idx) => `http://api.tvmaze.com/shows/${idx + 1}`,
);
const handleResponse = data => {
const shows = data.map(show => show.data);
this.setState({
isLoading: false,
title: shows.map(show => show.name),
image: shows.map(show => show.image.medium),
rating: shows.map(show => show.rating.average),
otherDetails:shows.map((show,index)=>{
return [
show.genres[index],
show.schedule[index],
show.language[index],
show.network[index],
show.summary[index],
];
}),
});
};
const handleError = error => {
this.setState({
isLoading: false,
});
};
console.log(this.state.otherDetails.genres);
Promise.all(requestUrls.map(url => axios.get(url)))
.then(handleResponse)
.catch(handleError);
};
render() {
const {isLoading, title, image, rating, otherDetails} = this.state;
if (isLoading) {
return <ActivityIndicator size="large" color="#0000ff" />;
}console.log(this.state);
return (
<View style={{flex: 1, alignItems: 'center', justifyContent: 'center'}}>
<View style={{backGroundColor: 'red'}} />
<ScrollView style={{flex: 1}}>
<Card
title={this.state.title}
rating={this.state.rating}
source={this.state.image}
navigation = {this.props.navigation}
/>
</ScrollView>
<Text>here images</Text>
</View>
);
}
}
any help would be nice thank you in advanced ...!
Storing the response from tvmaze as an array instead of trying to map all the values to keys would make your life a bit easier.. Something like this should work:
import axios from 'axios'
import React from 'react'
import { ActivityIndicator, ScrollView, Text, View } from 'react-native'
import Card from '../Components/Card/card'
export default class HomeScreen extends React.Component {
state = {
shows: [],
isLoading: true
}
componentDidMount () {
this.getData()
}
getData = () => {
const requestUrls = Array.from({length: 9}).map(
(_, idx) => `http://api.tvmaze.com/shows/${idx + 1}`
)
const handleResponse = data => {
console.log(data)
this.setState({
isLoading: false,
shows: data
})
}
const handleError = error => {
console.log(error)
this.setState({
isLoading: false
})
}
Promise.all(requestUrls.map(url => axios.get(url)))
.then(handleResponse)
.catch(handleError)
}
render () {
const {isLoading, shows} = this.state
if (isLoading) {
return <ActivityIndicator size='large' color='#0000ff' />
}
console.log(this.state)
return (
<View style={{flex: 1, alignItems: 'center', justifyContent: 'center'}}>
<View style={{backGroundColor: 'red'}} />
<ScrollView style={{flex: 1}}>
{shows.length && shows.map(show => (
<Card key={show.data.id}
title={show.data.name}
{/*navigation={this.props.navigation}*/}
/>
))}
</ScrollView>
<Text>here images</Text>
</View>
)
}
}

Invariant Violation in React Native

I am trying to use ListView on my js page and I am getting no data on my screen. The screen is totally blank. Below is the image of the empty screen. I am getting a warning.
Below is my code where I am calling the ListView:
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';
const styles = StyleSheet.create({
container: {
flex: 1,
width: 353,
flexWrap: 'wrap',
paddingTop: 20,
paddingLeft: 20,
},
});
const store = createStore(reducers);
class AutoCompActivity extends Component {
componentWillMount() {
const ds = new ListView.DataSource({
rowHasChanged: (r1, r2) => r1 !== r2,
});
this.dataSource = ds.cloneWithRows(this.props.services);
}
render() {
return (
<Provider store={store}>
<View style={styles.container}>
<ListView
enableEmptySections={true}
dataSource={this.dataSource}
renderRow={(rowData) =>
<ServiceItem services={rowData} />
}
/>
</View>
</Provider>
);
}
}
const mapStateToProps = state => {
return { services: state.services };
};
const ConnectedAutoCompActivity = connect(mapStateToProps)(AutoCompActivity);
const app1 = () => (
<Provider store={store}>
<ConnectedAutoCompActivity />
</Provider>
)
export default app1;
My ServiceItem.js file is below:
import React from 'react';
import { StyleSheet, Text, View, Button, ImagePropertiesAndroid } 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(
<View>
<Text style={[theme.cardTitleStyle, styles.title]}>{props.services.services}</Text>
</View>
)
}
export default connect(null, actions)(ServiceItem);
My Json file is very simple:
[
{
"services": "Test1"
},
{
"services": "Test2"
},
{
"services": "Test3"
},
{
"services": "Test4"
},
{
"services": "Test4"
}
]
My service.Reducer has the following code:
import services from './services.json';
const initialState = {
services
};
export default (state = initialState, action) => {
switch (action.type) {
default:
return state;
}
}
I checked my code several times and could not find any issue. I also installed react redux. Store is defined as const in my code. I am just trying to show each service as
test1,
test2 on my phone
Any help will be greatly appreciated.
The problem here is that you are using Provider inside connected component.
The connected component should be wrapped inside <Provider>. Replace your code with the following and it will work as expected.
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';
const styles = StyleSheet.create({
container: {
flex: 1,
width: 353,
flexWrap: 'wrap',
paddingTop: 20,
paddingLeft: 20,
},
});
const store = createStore(reducers);
class AutoCompActivity extends Component {
componentWillMount() {
const ds = new ListView.DataSource({
rowHasChanged: (r1, r2) => r1 !== r2,
});
this.dataSource = ds.cloneWithRows(this.props.services);
}
render() {
return (
<Provider store={store}>
<View style={styles.container}>
<ListView
enableEmptySections={true}
dataSource={this.dataSource}
renderRow={(rowData) =>
<ServiceItem services={rowData} />
}
/>
</View>
</Provider>
);
}
}
const mapStateToProps = state => {
return { services: state.services };
};
const ConnectedAutoCompActivity = connect(mapStateToProps)(AutoCompActivity);
const App = () => (
<Provider store={store}>
<ConnectedAutoCompActivity />
</Provider>
)
export default App;

Resources