How do I add items to array in following format and display it in flatlist? - react-native

I am trying to add items to redux state array. I can add items but my flatlist doesn't display them. It's most likely because they are like this ['abc-123, bcd-234'] etc. instead of [{license: abc-123}] so I could call the item.license in my flatlist. And how would I add an id to these items. How can I fix my structure a bit to get the [{id: 0, license: 'abc-123'}] ?
This is my action file:
const ADD_NEW_CAR = 'ADD_NEW_CAR'
const DELETE_EXISTING_CAR = 'DELETE_EXISTING_CAR'
export const addNewCar = (text) => ({
type: ADD_NEW_CAR,
payload: text
})
export const deleteExistingCar = (license) => ({
type: DELETE_EXISTING_CAR,
payload: license
})
this is my reducer:
const ADD_NEW_CAR = 'ADD_NEW_CAR'
const DELETE_EXISTING_CAR = 'DELETE_EXISTING_CAR'
const initialState = {
cars: [],
}
const carsListReducer = (state = initialState, action) => {
switch (action.type) {
case ADD_NEW_CAR:
return {
...state,
cars: [...state.cars, action.payload],
}
case DELETE_EXISTING_CAR:
return {
cars: [
...state.cars.filter(license => license !== action.payload)
]
}
default:
return state
}
}
export default carsListReducer
and this is my flatlist:
const totalCars = props.cars.length
<FlatList
style={{ marginTop: 0 }}
data={cars}
keyExtractor={(item) => item.id}
renderItem={({ item }) => {
return (
<View style={licenseContainer}>
<View style={{ width: '20%' }}>
<Ionicons
style={carIcon}
name='car-outline'
size={30}
color={colors.black}
/>
</View>
<View style={{ width: editing ? '60%' : '80%' }}>
<Text key={item.license} style={licenseText}>
{item.license}
</Text>
</View>
{editing ? (
<View style={{ width: '20%' }}>
<Ionicons
name='ios-close-circle-outline'
size={30}
color={colors.black}
style={removeIcon}
onPress={() => removeCar(item.license)}
/>
</View>
) : null}
</View>
)
}}
ItemSeparatorComponent={() => {
return <View style={divider} />
}}
/>
const mapStateToProps = (state) => ({
signedIn: state.authReducer.signedIn,
cars: state.cars
})
const mapDispatchToProps = (dispatch) => ({
authActions: bindActionCreators(authAction, dispatch),
addNewCar: text => dispatch(addNewCar(text)),
deleteExistingCar: car => dispatch(deleteExistingCar(car))
})
export default connect(mapStateToProps, mapDispatchToProps)(ProfileScreen)

If your array contains string values then instead of using item.license just use item
<View style={{ width: editing ? '60%' : '80%' }}>
<Text key={item} style={licenseText}>
{item}
</Text>
</View>

Related

Remove an item from FlatList render wrong items

I know that it has been asked several times, but in all the other threads the problem is that the author is manipulating the state directly - which I don't (hopefully).
I've got an array of posts that I get from the DB.
I want to be able to filter this array according to the tags each post has. In order to do so, I'm filtering the array, saving the result in a temp array, and then setting another array that holds the current posts to display again using useState. The filter works properly.
The list of posts is rendered in a FlatList
<FlatList
data={filteredPosts}
extraData={refreshFlat}
style={globalStyles.feed}
renderItem={({ item }) => (
<Post
post={item}
navigation={navigation}
style={globalStyles.list_of_posts}
/>
)}
refreshing={refreshing}
onRefresh={handleRefresh}
ListEmptyComponent={() => {
return (
<View>
<Text style={globalStyles.be_first}>
נראה שאין מה להציג כרגע..
</Text>
</View>
);
}}
ItemSeparatorComponent={() => {
return <View style={{ height: 12 }}></View>;
}}
keyExtractor={(item, index) => index.toString()}
ListHeaderComponent={getHeader}
/>
But when I re-render the list, the wrong items are shown.
For example, if the list contains only one post after the filter, the FlatList will display only the first item of the original list.
Just to make clear, the item is the right item, I used console.log both outside and inside the Post component to validate it.
postsList - Holds the original list
filteredPosts - Holds the current posts that I want to display
refreshFlat - I tried to force it to refresh using extraData
The complete component:
import { Text, Pressable, FlatList, View, Modal } from "react-native";
import { globalStyles } from "../../styles/global";
import React, { useState, useEffect } from "react";
import Post from "../../API/Post";
import { useData } from "../../AuthProvider/UserDataProvider";
const FeedScreen = ({ navigation, route }) => {
const [refreshing, setRefreshing] = useState(true);
const { getPosts, tagsList, getTags } = useData();
const [postsList, setPostsList] = useState([]);
const [modalVisible, setModalVisible] = useState(false);
const [selectedTags, setSelectedTags] = useState([]);
const [filteredPosts, setFilteredPosts] = useState([]);
const [refreshFlat, setRefreshFlat] = useState(false);
const handleRefresh = () => {
getPosts()
.then((posts) => {
setPostsList(posts);
setFilteredPosts(posts);
setSelectedTags([]);
setRefreshing(false);
})
.catch(console.error);
};
const handleSelectTag = (tag) => {
if (selectedTags.includes(tag)) {
const temp = selectedTags.filter((currTag) => currTag !== tag);
setSelectedTags(temp);
} else {
setSelectedTags((prev) => [...prev, tag]);
}
};
const filterPosts = (tags) => {
if (tags.length === 0) return setFilteredPosts([...postsList]);
const temp = postsList.filter((post) =>
post.data.tags.some((t) => tags.includes(t))
);
console.log(temp);
setFilteredPosts(temp);
setRefreshFlat((prev) => !prev);
};
const getHeader = () => {
return (
<View>
<Modal
visible={modalVisible}
animationType="slide"
onRequestClose={() => {
setModalVisible((prev) => !prev);
}}
>
<View>
<FlatList
data={tagsList}
renderItem={({ item }) => (
<Pressable
style={{
backgroundColor: selectedTags.includes(item.name)
? "green"
: "#EAE7E6",
padding: 5,
margin: 5,
}}
onPress={() => handleSelectTag(item.name)}
>
<Text>{item.name}</Text>
</Pressable>
)}
numColumns={3}
ListEmptyComponent={() => {
return (
<View>
<Text style={globalStyles.be_first}>
נראה שאין מה להציג כרגע..
</Text>
</View>
);
}}
ItemSeparatorComponent={() => {
return <View style={{ height: 12 }}></View>;
}}
keyExtractor={(item, index) => index.toString()}
/>
</View>
<Pressable
onPress={() => {
filterPosts(selectedTags);
setModalVisible(false);
}}
style={{ marginLeft: 10, width: 50, height: 50 }}
>
<Text>{"סנן"}</Text>
</Pressable>
</Modal>
<Pressable
onPress={() => setModalVisible(true)}
style={{ width: "100%", height: 50 }}
>
<Text>{"open modal"}</Text>
</Pressable>
</View>
);
};
useEffect(() => {
getPosts()
.then((posts) => {
setPostsList(posts);
setFilteredPosts(posts);
setRefreshing(false);
})
.catch(console.error);
getTags();
return;
}, []);
return (
<View style={{ flex: 1 }}>
<FlatList
data={filteredPosts}
extraData={refreshFlat}
style={globalStyles.feed}
renderItem={({ item }) => (
<Post
post={item}
navigation={navigation}
style={globalStyles.list_of_posts}
/>
)}
refreshing={refreshing}
onRefresh={handleRefresh}
ListEmptyComponent={() => {
return (
<View>
<Text style={globalStyles.be_first}>
נראה שאין מה להציג כרגע..
</Text>
</View>
);
}}
ItemSeparatorComponent={() => {
return <View style={{ height: 12 }}></View>;
}}
keyExtractor={(item, index) => index.toString()}
ListHeaderComponent={getHeader}
/>
<Pressable
title="edit"
onPress={() => {
navigation.navigate("CreateProject");
}}
style={globalStyles.plus_btn}
>
<Text style={globalStyles.plus_btn_text}>+</Text>
</Pressable>
</View>
);
};
export default FeedScreen;
Maybe it's the key extractor issue? You are using the index of the array as the key and it could confuse the flatlist when you update the data.

initialState resets after dispatch actions in react useReducer

In my app, I fetch users data from the server inside the useEffect hook and set the initialState of the useReducer. When action dispatch happens on text input change, the initialState resets instead of updating thus I can't type a word inside the input. Can someone figure out the problem, please? I'm fairly new to react reducers. I have attached the relevant codes. Thanks.
EditProfile.js
const EditProfile = ({ navigation, route }) => {
const userid = route.params.userid;
const { user } = React.useContext(AuthContext);
const [userData, setUserData] = React.useState(null);
const initialState = {
name: userData ? (userData.name ? userData.name : "") : "",
dob: userData ? (userData.dob ? userData.dob.toDate() : "") : "",
phone: userData ? (userData.phone ? userData.phone : "") : "",
location: userData ? (userData.location ? userData.location : "") : "",
caption: userData ? (userData.caption ? userData.caption : "") : "",
};
React.useEffect(() => {
async function fetchData() {
const response = await getUserData(userid);
setUserData(response);
}
fetchData();
}, []);
const reducer = (state, action) => {
switch (action.type) {
case "nameInputChange":
return {
...state,
name: action.name,
};
case "dobInputChange":
return {
...state,
dob: action.dob,
};
case "phoneInputChange":
return {
...state,
phone: action.phone,
};
case "locationInputChange":
return {
...state,
location: action.location,
};
case "captionInputChange":
return {
...state,
caption: action.caption,
};
}
};
const [data, dispatch] = React.useReducer(reducer, initialState);
const nameInputChange = (value) => {
dispatch({
type: "nameInputChange",
name: value,
});
console.log("Name: ", initialState.name);
};
const dobInputChange = (date) => {
dispatch({
type: "dobInputChange",
dob: date,
});
};
const phoneInputChange = (value) => {
dispatch({
type: "phoneInputChange",
phone: value,
});
};
const locationInputChange = (value) => {
dispatch({
type: "locationInputChange",
location: value,
});
};
const captionInputChange = (value) => {
dispatch({
type: "captionInputChange",
caption: value,
});
};
return (
<View>
<FlatList
showsVerticalScrollIndicator={false}
ListHeaderComponent={() => (
<View>
<TouchableOpacity>
<Image
source={require("../assets/images/profile.jpg")}
style={{ width: "98%", height: "98%", borderRadius: 59 }}
/>
<View>
<Entypo name="camera" color="#8000e3" size={18} />
</View>
</TouchableOpacity>
<View>
<VerticalNameInput
type="name"
label="Full Name"
placeholder="Full name"
color="#9798ac"
placeholder="enter your full name"
onChangeText={(value) => nameInputChange(value)}
value={initialState.name}
/>
<VerticalDateInput
label="Date of Birth"
color="#9798ac"
dobInputChange={dobInputChange}
initialState={initialState}
/>
</View>
<View>
<VerticalNameInput
type="mobile"
label="Mobile"
color="#9798ac"
placeholder="mobile number"
onChangeText={(value) => phoneInputChange(value)}
value={initialState.phone}
/>
<VerticalNameInput
type="location"
label="Location"
color="#9798ac"
placeholder="city and country"
onChangeText={(value) => locationInputChange(value)}
value={initialState.location}
/>
</View>
<View>
<VerticalNameInput
type="caption"
label="Profile Caption"
color="#9798ac"
placeholder="enter about yourself"
onChangeText={(value) => captionInputChange(value)}
value={initialState.caption}
/>
</View>
</View>
)}
/>
<View style={{ position: "relative", top: -90, left: 200 }}>
<FloatingAction
onPressMain={() => {
updateUser(userid, userData);
}}
floatingIcon={<Entypo name="check" size={28} color="#fff" />}
/>
</View>
</View>
);
};
export default EditProfile;
VerticalNameInput.js
const VerticalNameInput = ({ label, color, placeholder, type, ...rest }) => {
return (
<View>
<Text>
{label}
</Text>
<View>
<View>
{type === "name" ? (
<AntDesign name="user" color="#000" size={15} />
) : type === "mobile" ? (
<AntDesign name="mobile1" color="#000" size={15} />
) : type === "location" ? (
<EvilIcons name="location" color="#000" size={20} />
) : type === "caption" ? (
<Ionicons
name="information-circle-outline"
color="#000"
size={18}
/>
) : null}
</View>
<TextInput
style={{ width: "85%", height: "100%" }}
numberOfLines={1}
placeholder={placeholder}
placeholderTextColor={color}
{...rest}
/>
</View>
</View>
);
};
export default VerticalNameInput;
VerticalDateInput.js
const VerticalDateInput = ({ label, color, dobInputChange, initialState }) => {
const [date, setDate] = React.useState(new Date());
const [open, setOpen] = React.useState(false);
return (
<View>
<Text>
{label}
</Text>
<View>
<View>
<AntDesign name="calendar" color="#000" size={15} />
</View>
<View>
<Text style={{ marginLeft: 10 }}>
{initialState.dob
? initialState.dob.toDateString()
: new Date().toDateString()}
</Text>
<TouchableOpacity
style={{ marginRight: 10 }}
onPress={() => setOpen(true)}
>
<AntDesign name="caretdown" color="#000" size={12} />
</TouchableOpacity>
</View>
<DatePicker
maximumDate={new Date()}
mode="date"
modal
open={open}
date={initialState.dob ? initialState.dob : date}
onConfirm={(date) => {
setOpen(false);
setDate(date);
dobInputChange(date);
}}
onCancel={() => {
setOpen(false);
}}
/>
</View>
</View>
);
};
export default VerticalDateInput;
Try add "default" case return current state in your reducer.
It might happen that you dispatch some unknown action, and reducer return undefined as a result.
const reducer = (state = initialState, action) => {
switch (action.type) {
default:
// If this reducer doesn't recognize the action type, or doesn't
// care about this specific action, return the existing state unchanged
return state
}
}

React child prop doesn't change when parent state updates

I have a react native app and I want to update some states and pass a prop to other components. I am passing the focus state and setFocus to the "Search" component. The focus state on the "Vault" component updates properly but it doesn't affect the "Search" component. The code is like below. What am I doing wrong?
const Vault = ({ navigation }: VaultStackNavigationProps<"Vault">) => {
const [focus, setFocus] = useState(false);
React.useLayoutEffect(() => {
navigation.setOptions({
headerRight: () => (
<Right isFocus={focus}>
<Search handleFocus={setFocus} focus={focus} />
</Right>
),
});
}, [navigation]);
return (
<Box style={{ flex: 1, backgroundColor: "#1A1A1A" }}>
<Text color="white">hello</Text>
</Box>
);
};
export const Search = ({ handleFocus, focus }) => {
const [value, setValue] = useState("");
const inputRef = useRef<TextInput>();
const { width } = useWindowDimensions();
const onHandleFocus = (value) => {
handleFocus(value);
};
useEffect(() => {
if (focus) {
inputRef.current.focus();
} else {
Keyboard.dismiss();
clearTextState();
}
}, [focus]);
const clearTextState = () => {
setValue("");
};
const onClear = () => {
clearTextState();
inputRef.current.clear();
};
const onClose = () => {
onHandleFocus(false);
};
return (
<>
{focus && (
<TouchableOpacity onPress={onClose}>
<MaterialIcons name="arrow-back" size={24} color="white" />
</TouchableOpacity>
)}
{focus && (
<TextInput
ref={inputRef}
style={{
flex: 1,
color: "white",
paddingLeft: 15,
fontFamily: "CrimsonRegular",
}}
onChangeText={(text) => setValue(text)}
placeholder="Type here"
/>
)}
{focus && value.length > 0 && (
<SearchIconButton
onPress={onClear}
style={{ width: width / 9 }}
icon="close"
/>
)}
</>
);
};
Your layoutEffect is listening changes only from navigation
Try adding focus to useLayoutEffect array like
React.useLayoutEffect(() => {
navigation.setOptions({
headerRight: () => (
<Right isFocus={focus}>
<Search handleFocus={setFocus} focus={focus} />
</Right>
),
});
}, [navigation, focus]);

How to pass a custom button in a drawer navigator, using the DrawerItemList in React Navigation v. 5?

I'm trying to migrate to react navigation 5, but I get an error where I use the DrawerItemList in place of the DrawerNavigatorItems.
My code used to look like this:
const MainNavigator = createDrawerNavigator(
// e.g.
Winners: {
screen: WinnersNavigator,
navigationOptions: {
drawerLabel: (
<BoldText style={NavigationStyles.arhiki}>Νικητές</BoldText>
),
drawerIcon: tabInfo => {
return (
<View style={NavigationStyles.winners}>
<FontAwesome
name="users"
size={iconMultiplier / 10}
color={tabInfo.tintColor}
/>
</View>
);
}
}
},
// ... more screens
contentComponent: props => {
const dispatch = useDispatch();
// This is for showing the Admin screen link, if user is an admin.
const userIdExists = useSelector(state => state.auth.userId);
return (
<View style={{ flex: 1 }}>
<SafeAreaView forceInset={{ top: "always", horizontal: "never" }}>
{/* These are the default drawer items */}
// THE PROBLEM IS HERE!!!
<DrawerNavigatorItems {...props} />
{/* Plus our custom buttons */}
{userIdExists && (
<View style={NavigationStyles.summary}>
<Ionicons.Button
name="ios-create"
backgroundColor={Colours.moccasin_light}
size={iconMultiplier / 10}
// style={{marginLeft: -20 }}
color="#888"
onPress={() => props.navigation.navigate("CreateWelcome")}
></Ionicons.Button>
<Text
onPress={() => props.navigation.navigate("CreateWelcome")}
style={[
NavigationStyles.exodos,
Platform.OS == "android" ? { marginLeft: -6 } : null
]}
>
Δημιουργία
</Text>
</View>
)}
...
Now it looks like this:
const CustomDrawerContent = props => {
const dispatch = useDispatch();
// This is for showing the Admin screen link, if user is an admin.
const userIdExists = useSelector(state => state.auth.userId);
return (
<View style={{ flex: 1 }}>
<SafeAreaView forceInset={{ top: "always", horizontal: "never" }}>
<DrawerContentScrollView {...props}>
{/* These are the default drawer items */}
<DrawerItemList {...props} />
{/* Plus our custom buttons */}
<Drawer.Section>
{userIdExists && (
<View style={NavigationStyles.summary}>
<DrawerItem
label={() => (
<Text
// onPress={() => props.navigation.navigate("CreateWelcome")}
style={[
NavigationStyles.exodos,
Platform.OS == "android" ? { marginLeft: -6 } : null
]}
>
Δημιουργία
</Text>
)}
icon={() => (
<Ionicons.Button
name="ios-create"
backgroundColor={Colours.moccasin_light}
size={iconMultiplier / 10}
// style={{marginLeft: -20 }}
color="#888"
// onPress={() => props.navigation.navigate("CreateWelcome")}
></Ionicons.Button>
)}
onPress={() => props.navigation.navigate("CreateWelcome")}
/>
</View>
)}
// ... more items
</Drawer.Section>
</DrawerContentScrollView>
</SafeAreaView>
</View>
);
};
const MainDrawerNavigator = createDrawerNavigator();
export const MainNavigator = () => {
return (
<MainDrawerNavigator.Navigator
drawerStyle={{
width: width < 900 ? 0.6 * width : 0.4 * width,
backgroundColor: Colours.moccasin_light,
overlayColor: Colours.maroonRGBA
}}
drawerContentOptions={{ activeTintColor: Colours.gr_brown }}
drawerContent={props => <CustomDrawerContent {...props} />}
>
<MainDrawerNavigator.Screen
name="GameNavigator"
component={GameNavigator}
options={{
drawerLabel: (
<BoldText style={NavigationStyles.arhiki}>Αρχική</BoldText>
),
drawerIcon: ({ color }) => (
<View style={NavigationStyles.shield}>
<MaterialCommunityIcons
name="shield-cross"
size={iconMultiplier / 8}
color={color}
/>
</View>
)
}}
/>
// ... more screens
</MainDrawerNavigator.Navigator>
);
};
The error I get is:
TypeError: label is not a function. (In 'label({
color: color,
focused: focused
})', 'label' is an instance of Object)
and it's generated at the <DrawerItemList {...props} />
In the docs I read:
import {
    DrawerContentScrollView,
    DrawerItemList,
  } from '#react-navigation/drawer';
  
  function CustomDrawerContent(props) {
    return (
      <DrawerContentScrollView {...props}>
        <DrawerItemList {...props} />
      </DrawerContentScrollView>
    );
  }
// To add additional items in the drawer, you can use the DrawerItem component:
function CustomDrawerContent(props) {
return (
<DrawerContentScrollView {...props}>
<DrawerItemList {...props} />
<DrawerItem
label="Help"
onPress={() => Linking.openURL('https://mywebsite.com/help')}
/>
</DrawerContentScrollView>
);
}
The first screen that I render is a Navigator, the GameNavigator.
Could that be a problem?
I read in a issue that:
"It's not possible to add navigators inside drawer content. You can achieve custom layouts using a custom router and custom navigator:" source,but I've learned from a course that it is possible! Or does this guy mean something else with drawer content?
The GameNavigator is:
const GameStackNavigator = createStackNavigator();
const GameNavigator = () => {
return (
<GameStackNavigator.Navigator
initialRouteName="Welcome"
screenOptions={defaultNavOptions}
>
<GameStackNavigator.Screen
name="Welcome"
component={WelcomeScreen}
options={WelcomeScreenOptions}
/>
...
</GameStackNavigator.Navigator>
);
};
And the WelcomeScreen is:
const WelcomeScreen = props => {
const dispatch = useDispatch();
const [isLoading, setIsLoading] = useState(false);
const [modalVisible, setModalVisible] = useState(false);
const [gridTileAnimValue] = useState(new Animated.Value(0));
const [isConnected, setIsConnected] = useState(false);
// For adding the points that are saved in memory, when connection is established.
useEffect(() => {
const unsub = NetInfo.addEventListener(state => {
setIsConnected(state.isConnected);
});
return () => unsub();
}, []);
const getPoints = async () => {
let points = await AsyncStorage.getItem("savedPoints");
if (!!points) {
const getEmail = async () => {
const userData = await AsyncStorage.getItem("userData");
if (userData) {
const transformedData = JSON.parse(userData);
const { userEmail } = transformedData;
return userEmail;
}
};
const email = await getEmail();
// Give it some time to get the token and userId,
// because saveData needs them.
setTimeout(
async () => await dispatch(dataActions.saveData(email, +points)),
3000
);
await AsyncStorage.removeItem("savedPoints");
}
};
if (isConnected) getPoints();
useEffect(() => {
getFilters = async () => {
await dispatch(filtersActions.fetchDifficultyLevelFilters());
await dispatch(filtersActions.fetchCategoriesFilters());
};
}, [dispatch]);
useEffect(() => {
props.navigation.setOptions({
headerRight: () => (
<HeaderButtons HeaderButtonComponent={CustomHeaderButton}>
<Item
title="game-info"
iconName={
Platform.OS === "android"
? "md-information-circle-outline"
: "ios-information-circle-outline"
}
// style={{width: width / 8, height: height / 10, paddingTop: height / 35}}
onPress={() => setModalVisible(!modalVisible)}
/>
</HeaderButtons>
)
});
}, [modalVisible, setModalVisible]);
useEffect(() => {
const checkIfInfoNeeded = async () => {
return await AsyncStorage.getItem("NO_infoNeeded");
};
checkIfInfoNeeded().then(NO_infoNeeded => {
if (NO_infoNeeded === "NO") {
return;
} else {
setModalVisible(true);
}
});
}, []);
const animateGridTile = () => {
Animated.timing(gridTileAnimValue, {
toValue: 1,
duration: 1200,
useNativeDriver: false
}).start();
};
useEffect(() => {
animateGridTile();
const unsubscribe = props.navigation.addListener("focus", animateGridTile);
return () => unsubscribe();
}, [animateGridTile]);
useEffect(() => {
const unsubscribe = props.navigation.addListener("willBlur", () =>
gridTileAnimValue.setValue(0)
);
return () => {
unsubscribe();
};
}, []);
const cardStyle = { opacity: gridTileAnimValue };
const renderGridItem = itemData => {
return (
<Animated.View style={cardStyle}>
<CategoryGridTile
color={itemData.item.color}
title={itemData.item.title}
id={itemData.item.id}
onSelect={() => {
if (itemData.item.id == 0) {
props.navigation.navigate({
routeName: "MixedChoicesScreen"
});
} else if (itemData.item.id == 1) {
props.navigation.navigate({
routeName: "MultiChoiceCategories",
params: {
gameType: itemData.item.title
}
});
} else if (itemData.item.id == 2) {
props.navigation.navigate({
routeName: "TrueFalseCategories",
params: {
gameType: itemData.item.title
}
});
}
}}
/>
</Animated.View>
);
};
if (isLoading) {
return (
<CustomLinearGradient>
<View style={styles.centered}>
<ActivityIndicator size="large" color={Colours.moccasin_light} />
</View>
</CustomLinearGradient>
);
}
return (
<CustomLinearGradient>
<View style={styles.flatListContainer}>
{modalVisible && (
<CustomModal
modalVisible={modalVisible}
setModalVisible={setModalVisible}
onRequestClose={() => {
Alert.alert(
"Επιλογές",
"Παρακαλώ επιλέξτε μία από τις δύο επιλογές της καρτούλας: Ναι ή Όχι.",
[{ text: "Εντάξει", style: "default" }]
);
// Alert.alert("Παρακαλώ επιλέξτε μία από τις δύο επιλογές της καρτούλας: Πληροφορίες ή Δεν χρειάζεται.");
}}
textOne="Θέλετε να διαβάσετε τις οδηγίες χρήσεως και τις πληροφορίες σχετικά με τις
δοκιμαστικές εκδόσεις της εφαρμογής."
buttonOneTitle="Ναι"
buttonTwoTitle="Όχι"
onPressOne={async () => {
AsyncStorage.setItem("NO_infoNeeded", "NO");
setModalVisible(false);
props.navigation.navigate("GameInfo");
}}
onPressTwo={async () => {
AsyncStorage.setItem("NO_infoNeeded", "NO");
setModalVisible(false);
}}
/>
)}
<FlatList
// numColumns={2}
keyExtractor={(item, index) => item.id}
data={GAME_TYPES}
renderItem={renderGridItem}
/>
</View>
</CustomLinearGradient>
);
};
export const WelcomeScreenOptions = ({ route, navigation }) => {
return {
title: "ΕΝ ΤΟΥΤΩ ΝΙΚΑ",
headerLeft: () => (
<HeaderButtons HeaderButtonComponent={CustomHeaderButton}>
<Item
onPress={() => navigation.toggleDrawer()}
title="Menu"
iconSize={73}
iconName={Platform.OS === "android" ? "md-menu" : "ios-menu"}
// style={{
// width: width / 8,
// height: height / 10,
// paddingTop: height / 35
// }}
/>
</HeaderButtons>
)
};
};
Any suggestion would be appreciated.
Thanks
For drawerLabel you have directly set an object which is wrong
drawerLabel: (
<BoldText style={NavigationStyles.arhiki}>Αρχική</BoldText>
),
This should be either a string or a function that returns a component, so you should change it like below
drawerLabel: {()=>(
<BoldText style={NavigationStyles.arhiki}>Αρχική</BoldText>
)},
You can refer the docs
https://reactnavigation.org/docs/drawer-navigator/#drawerlabel

Tabbed navigation between screens in react native

I use a StackNavigator based on the react-native-elements example and I want to enable something similar to a link with an ID as a parameter. I want to link to this screen:
const FontsTab = StackNavigator({
Home: {
screen: FontsTabView,
path: '/',
navigationOptions: ({ navigation }) => ({
title: 'Fonts',
headerLeft: (
<Icon
name="menu"
size={30}
type="entypo"
style={{ paddingLeft: 10 }}
onPress={() => navigation.navigate('DrawerOpen')}
/>
),
}),
},
Detail: {
screen: FontsDetailTabView,
path: 'fonts_detail',
navigationOptions: {
title: 'Fonts Detail',
},
},
});
I have this screen where I want the click of the text of an item to open the FontsTabView with the ID as a parameter. I would like to achieve something like the following:
<Text onPress={ (navigation)=> navigation.navigate('FontsTabView ', { id: {item.id} }) } style={styles.listHeader} >{item.title}</Text>
How can it be done?
class Icons extends Component {
constructor() {
super();
const ds = new ListView.DataSource({
rowHasChanged: (r1, r2) => r1 !== r2,
});
this.state = {
selectedIndex: 0,
value: 0.5,
dataSource: ds.cloneWithRows(list1),
isLoading: true
};
this.updateIndex = this.updateIndex.bind(this);
this.renderRow = this.renderRow.bind(this);
}
updateIndex(selectedIndex) {
this.setState({ selectedIndex });
}
renderRow(rowData, sectionID) {
return (
<ListItem
key={sectionID}
onPress={log}
title={rowData.title}
icon={{ name: rowData.icon }}
/>
);
}
_renderList = ({ item, navigation }) => {
return (
<TouchableWithoutFeedback onPress={(event) => this._selectedItem(item.key)}>
<View style={styles.listRowContainer}>
<View style={styles.listinside1Container}>
<Image style={styles.listImage} source={item.icon} />
<View style={styles.listContainer} onPress={(event) => this._selectedItem(item.text)} >
<Text onPress={ (navigation)=> navigation.navigate('DrawerOpen') } style={styles.listHeader} >{item.title}</Text>
<Text style={styles.listValue} >{item.value}</Text>
<Image
style={{width: 50, height: 50}}
source={{uri: item.img}}
/>
</View>
</View>
</View>
</TouchableWithoutFeedback>
);
}
componentDidMount(){
return fetch('https://www.koolbusiness.com/in.json')
.then((response) => response.json())
.then((responseJson) => {
this.setState({
isLoading: false,
dataSource: responseJson.movies,
}, function(){
});
})
.catch((error) =>{
console.error(error);
});
}
render() {
if(this.state.isLoading){
return(
<View style={{flex: 1, padding: 20}}>
<ActivityIndicator/>
</View>
)
}
const { navigation } = this.props;
const buttons = ['Button1', 'Button2'];
const { selectedIndex } = this.state;
if(this.state.isLoading){
return(
<View style={{flex: 1, padding: 20}}>
<ActivityIndicator/>
</View>
)
}
return (
<ScrollView>
<View style={styles.headerContainer}>
<Icon color="white" name="invert-colors" size={62} />
<Text style={styles.heading}>Trending Ads India</Text>
</View>
<View style={styles.MainContainer}>
</View>
<View style={styles.mainWrapper} >
<FlatList data={this.state.dataSource} renderItem={this._renderList} keyExtractor={(item, index) => index.toString()} />
</View>
</ScrollView>
);
}
}
You were close but not quite there,
Try to render your item like below;
<Text onPress={ ()=> this.props.navigation.navigate('FontsTabView', { id: item.id }) } style={styles.listHeader} >
{item.title}
</Text>
Then in FontsTabView you can read the parameter like below and render your screen accordingly.
this.props.navigation.state.params.id