React-Native modal not showing FlatList Items - react-native

Modal only displays button but not FlatList item.
I am trying to build a custom app picker for my react-native-app which renders a list of items on a modal.
AppPicker.js
const AppPicker = ({ icon, items, placeholder }) => {
const [modalVisible, setModalVisible] = React.useState(false)
return (
<>
<TouchableWithoutFeedback onPress={() => setModalVisible(true)} >
<View style={styles.container}>
{icon && <MaterialCommunityIcons name={icon} size={20} style={styles.icon} />}
<AppText style={styles.text}> {placeholder} </AppText>
<MaterialCommunityIcons name="chevron-down" size={20} />
</View>
</TouchableWithoutFeedback>
<Modal visible={modalVisible} animationType="slide" >
<Button title="Close" onPress={() => setModalVisible(false)} />
<FlatList
data={items}
keyExtractor={item => item.value.toString()}
renderItem={({ item }) =>
<PickerItem
lable={item.label}
onPress={() => console.log(item)}
/>}
/>
</Modal>
</>
)
}
the <PickerItem/> that should be rendered by the flatlist is a component that just displays the items from the list.
PickerItem.js
const PickerItem = ({ label, onPress }) => {
return (
<TouchableOpacity onPress={onPress}>
<AppText> {label} </AppText>
</TouchableOpacity>
)
}
export default PickerItem;
when I randomly tap on the modal screen however the onPress() on the FlatList triggers the console.log(item) and the items are displayed on the console. Any help on this will be appreciated.
** App.js **
const categories = [
{ label: "furniture", value: 1 },
{ label: "clothing", value: 2 },
{ label: "phone", value: 3 },
]
export default function App() {
return (
<Screen style={styles.container}>
<AppPicker items={categories} icon="apps" placeholder="category" />
<AppTextInput icon="email" placeholder="email" />
</Screen>
);
}
NOTE: I am using expo to run the application.

Related

I am not able to navigate to the other screen in my react native project the error is: navigation not found

const Item = ({ item }) => (
<TouchableOpacity
onPress={() => this.navigation.navigate(
"carProfile",
{item: item}
)}>
<View style={styles.item}>
<Text style={styles.title}>{item.name}</Text>
<Text style={styles.details}>{item.details}</Text>
</View>
</TouchableOpacity>
);
const List = (props,navigation) => {
const renderItem = ({ item }) => {
if (props.searchPhrase === "") {
return <Item item={item} />;
}
if (item.name.toUpperCase().includes(props.searchPhrase.toUpperCase().trim().replace(/\s/g, ""))) {
return <Item item={item} />;
}
if (item.details.toUpperCase().includes(props.searchPhrase.toUpperCase().trim().replace(/\s/g, ""))) {
return <Item item={item} />;
}
};
return (
<SafeAreaView style={styles.list__container}>
<View
onStartShouldSetResponder={() => {
props.setClicked(false);
}}
>
<FlatList
data={props.data}
renderItem={renderItem}
keyExtractor={(item) => item.id}
/>
</View>
</SafeAreaView>
);
};
export default List;
the error is continuing to be there despite me trying to put navigation container in different positions. I want to send the user to the carProfile page, where the data passed in item is reused. This way user can know about the selection they are looking for
Use this way
onPress={() => this.props.navigation.navigate(
"carProfile",
{item: item}
)}
The navigation is inside the props, not as a second argument. Below is a classic example. And also note, you cannot extract navigation prop for child components, it will only work on Main components(Screens).
function HomeScreen({ navigation }) {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Home Screen</Text>
<Button
title="Go to Details"
onPress={() => navigation.navigate('Details')}
/>
</View>
);
}
If you want to use navigation inside child components, you can use the navigation hooks.
import { useNavigation } from "#react-navigation/native";
function MyBackButton() {
const navigation = useNavigation();
return (
<Button
title="Back"
onPress={() => {
navigation.goBack();
}}
/>
);
}

Flatlist doesn't display the list from useContext

In react native app, I have a home screen and a second screen that the user uses to add items that should be displayed on the home screen. I am using context to save the list of items. The problem is when I add items to the second screen and go to the home screen. The displayed list is empty.
Any help to explain why this happens and how to handle it? Here's the
Data Context
export const ExpenseContext = createContext();
App.js
const Stack = createNativeStackNavigator();
function App() {
const [expenseList, setExpenseList] = useState([]);
return (
<NavigationContainer>
<ExpenseContext.Provider value={{ expenseList, setExpenseList }}>
<Stack.Navigator>
<Stack.Screen
name="Home"
component={Home}
options={{ title: "Dashboard" }}
/>
<Stack.Screen
name="AddItem"
component={AddItem}
options={{ title: "CashFlowCreate" }}
/>
</Stack.Navigator>
</ExpenseContext.Provider>
</NavigationContainer>
);
}
export default App;
Home.js
function Home({ route, navigation }) {
const { expenseList } = useContext(ExpenseContext);
return (
<View style={styles.container}>
<Text style={styles.text}>Budget:</Text>
<Button title="+" onPress={() => navigation.navigate("AddItem")} />
<View>
<FlatList
style={styles.listContainer}
data={expenseList}
renderItem={(data) => <Text>{data.item.name}</Text>}
/>
</View>
</View>
);
}
export default Home;
AddItem.js
function AddItem({ navigation }) {
const { expenseList, setExpenseList } = useContext(ExpenseContext);
const [name, setName] = useState("");
const [amount, setAmount] = useState("");
const itemsList = expenseList;
return (
<View style={styles.container}>
<TextInput
style={styles.input}
onChangeText={(name) => setName( name )}
value={name}
placeholder="Name"
keyboardType="default"
/>
{name === "" && (
<Text style={{ color: "red", fontSize: 12, paddingLeft: 12 }}>
Name is required
</Text>
)}
<TextInput
style={styles.input}
onChangeText={(amount) => setAmount( amount )}
value={amount}
placeholder="Amount"
keyboardType="numeric"
/>
{amount === "" && (
<Text style={{ color: "red", fontSize: 12, paddingLeft: 12 }}>
Amount is required
</Text>
)}
<Button
title="Add"
style={styles.btn}
onPress={() => {
if (name === "" || amount === "") {
alert("Please Enter the required values.");
} else {
itemsList.push({
name: name,
amount: amount,
});
setExpenseList(itemsList);
}
}}
/>
<Button
title="View Dashboard"
style={styles.btn}
onPress={() => {
navigation.navigate("Home");
}}
/>
</View>
);
}
export default AddItem;
I solve it, in AddItem component remove const itemsList = expenseList; and onPress add button it should be like that instead
onPress={() => {
name === "" || amount === ""
? alert("Please Enter the required values.")
: setExpenseList([
...expenseList,
{
key:
Date.now().toString(36) +
Math.random().toString(36).substr(2),
name: name,
amount: amount,
},
]);
}}
I added the key because I needed later on.
There are several areas of issues in your code. One issue I can see is in AddItem. When you set:
const itemsList = expenseList
I think you did this for:
itemsList.push({
name: name,
amount: amount,
});
But you should look at the spread operator and try:
setExpenseList(...expenseList, {
name,
amount,
})
rewrite of AddItem.js:
function AddItem({ navigation }) {
const { expenseList, setExpenseList } = useContext(ExpenseContext)
const [name, setName] = useState('')
const [amount, setAmount] = useState('')
return (
<View style={styles.container}>
<TextInput style={styles.input} onChangeText={setName} value={name} placeholder='Name' keyboardType='default' />
{name === '' ? <Text style={styles.err}>Name is required</Text> : null}
<TextInput style={styles.input} onChangeText={setAmount} value={amount} placeholder='Amount' keyboardType='numeric' />
{amount === '' ? <Text style={styles.err}>Amount is required</Text> : null}
<Button
title='Add'
style={styles.btn}
onPress={() => {
name === '' || amount === ''
? alert('Please Enter the required values.')
: setExpenseList(...expenseList, {
name: name,
amount: amount,
})
}}
/>
<Button title='View Dashboard' style={styles.btn} onPress={() => navigation.navigate('Home')} />
</View>
)
}
export default AddItem
In your Home.js your FlatList it's missing the keyExtractor and you're trying to declare a prop of title outside of <Text>, rewrite:
function Home({ navigation }) {
const { expenseList } = useContext(ExpenseContext);
return (
<View style={styles.container}>
<Text style={styles.text}>Budget:</Text>
<Button title="+" onPress={() => navigation.navigate("AddItem")} />
<View>
<FlatList
style={styles.listContainer}
data={expenseList}
keyExtractor={(_,key) => key.toString()}
renderItem={(data) => <Text>{data.item.name}</Text>}
/>
</View>
</View>
);
}
export default Home;
Edit:
Answering to the comment. My understanding of the docs that is incorrect because keyExtractor is for identifying the id and by your commented code unless your passed in data to FlatList has a property of key then that wont work.
Also if key is not a string it should be:
keyExtractor={(item) => item.key.toString()}

React Native Flatlist with radio buttons works slow

I have flatlist with custom radio buttons implementaion, but when i tap on flatlist item it waits about second before changes to active button. I tried to useCallback with my renderItem and itemKeyExtractor functions but it doesnt help me.
Here is the code of my screen component:
export const PickOrganizationScreen = (props) => {
const { navigation, setOrganization, loadProcedureProviders, items, isLoading, procedureId, organizationId } = props;
useFocusEffect(
React.useCallback(()=>{loadProcedureProviders(procedureId);},[loadProcedureProviders, procedureId])
);
const renderItem = ({item}) => {
return (
<OrganizationItem
title={item.Title}
checked = {item.Id === organizationId}
onPress={() => {
setOrganization(item.Id, item.Title);
}}
/>);
};
const itemKeyExtractor = (item) => item.Id;
return (
isLoading ? (
<Spinner />
) : (
items.length > 0 ? (
<View style={styles.container}>
<View style={styles.paragraph}>
<Text style={styles.subtitle}>{I18n.t('pickOrganization')}</Text>
</View>
<View style={styles.alertMessage}>
<View style={styles.alertIcon}>
<Icon name="info" width={32} height={32} fill={Colors.primaryRed} />
</View>
<View>
<Text style={styles.alertText}>{I18n.t('pickOrganizationToRegisterService')}</Text>
</View>
</View>
<FlatList
data = {items}
renderItem = {renderItem}
keyExtractor = {itemKeyExtractor}
extraData={organizationId}
/>
<View style={styles.buttonWrapper}>
<ScreenButton
title={I18n.t('goToRegister')}
onPress={ () => {
navigation.navigate('ServiceSummary');
}}/>
</View>
</View>
) : (
<NotFound extraText={I18n.t('notFoundExtra')}/>
)
)
);
};
Here is the code of flatlist item component:
export const OrganizationItem = ({title, checked, onPress}) => {
return (
<TouchableOpacity onPress={onPress}>
<View style={styles.itemContainer}>
<View style={styles.itemIcon}>
{ checked ? (
<Icon name="radio-button-on" width={16} height={16} fill={Colors.primaryRed} />
) :
(
<Icon name="radio-button-off" width={16} height={16} fill={Colors.gray} />
)
}
</View>
<View style={styles.itemText}>
<Text style={styles.title}>{title}</Text>
</View>
</View>
</TouchableOpacity>
);
};
Try memoizing OrganizationItem. Does the onPress in OrganizationItem change the items object ? If so, it will re-render the whole Flatlist even when one small change is made. If you memoize, the components memoized won't rerender unless the props passed to it changes.
export const OrganizationItem = React.memo(({title, checked, onPress}) => {
return (
<TouchableOpacity onPress={onPress}>
<View style={styles.itemContainer}>
<View style={styles.itemIcon}>
{ checked ? (
<Icon name="radio-button-on" width={16} height={16} fill={Colors.primaryRed} />
) :
(
<Icon name="radio-button-off" width={16} height={16} fill={Colors.gray} />
)
}
</View>
<View style={styles.itemText}>
<Text style={styles.title}>{title}</Text>
</View>
</View>
</TouchableOpacity>
);
});

React Native functional component navigationOptions headerRight not being set

Previously I have set the headerRight option in the root component that renders child component with Screen options like this
export default function App() {
return (
<RecipeProvider>
<NavigationContainer>
<Stack.Navigator initialRouteName="Recipes">
<Stack.Screen
name="Recipes"
component={RecipeList}
options={({ navigation }) => ({
headerRight: () => (
<TouchableOpacity
style={styles.button}
onPress={() => navigation.navigate("New Recipe")}
>
<FontAwesomeIcon icon={faPlus} size={20} />
</TouchableOpacity>
),
})}
/>
and now I would like to move the headerRight inside the component definition (so I don't end up with a huge App file with details that are only relevant to the screen component themselves)
I have read other solutions and tried the following
export default function RecipeList({ navigation }) {
const { recipes } = useContext(RecipeContext);
return (
<View style={styles.container}>
<FlatList
numColumns={2}
data={recipes}
keyExtractor={(recipe: Recipe) => recipe.id}
renderItem={({ item }) => {
return (
<RecipeItem
name={item.name}
minutes={item.minutes}
image={item.image}
title="Go to Detail Screen"
onPress={() => {
navigation.navigate("Recipe Details", { item });
}}
/>
);
}}
/>
</View>
);
}
RecipeList.navigationOptions = ({ navigation }) => ({
headerRight: () => (
<TouchableOpacity
style={styles.button}
onPress={() => navigation.navigate("New Recipe")}
>
<FontAwesomeIcon icon={faPlus} size={20} />
</TouchableOpacity>
),
});
But the headerRight button doesn't show no more ... any ideas ?
Thank you all <3
My headerRight is below and it works for me
EditScreen.navigationOptions = navData => {
const submitFn = navData.navigation.getParam('submit');
return {
headerTitle: 'Edit Data'
headerRight: (
<HeaderButtons HeaderButtonComponent={HeaderButton}>
<Item
title="Save"
iconName={
Platform.OS === 'android' ? 'md-checkmark' : 'ios-checkmark'
}
onPress={submitFn}
/>
</HeaderButtons>
)
};
};

react naviagation v5 navigate from drawer custom view

I am using React Navigation V5, I wanna custom drawer Navigation content which contents the image on top and some others navigation items unders
Here is my drawer items:
Image (custom view)
Profile
Products
Orders
Here is my code my custom drawer content.
export const CustomDrawerContent = props => {
return (
<SafeAreaView style={styles.customDrawer}>
<View
style={{ flex: 1 }}
>
<DrawerContentScrollView {...props}>
<TouchableNativeFeedback onPress={() => { console.log('go profile'); }}>
<View style={styles.userContainer}>
<View style={styles.imageContainer}>
<Image
style={styles.image}
source={{ uri: 'https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcTLCta_MQcJFd2kpz8HwXFm-6vxVqXzRUgCOIuhs94Q32GG8EeJ' }}
/>
</View>
<Text style={styles.name}>Nguyen van Admin</Text>
</View>
</TouchableNativeFeedback>
<DrawerItemList {...props} />
</DrawerContentScrollView>
<DrawerItem
label="Đăng xuất"
style={{
borderWidth: 1,
}}
labelStyle={{
color: 'black'
}}
icon={({ focused, color, size }) => <Ionicons
size={23}
color={color}
name={Platform.OS === 'android' ? 'md-exit' : 'ios-exit-outline'}
/>}
/>
</View>
</SafeAreaView>
);
}
So If the profile screen existed in drawer, By clicking to the image i can use
props.navigate("profile")
But if I remove the profile screen from the drawer screens. I can not navigate to profile anymore.
How do i archive navigate to profile screen without adding it the drawer screens?
Or Can I hide profile item from drawer items?
To hide a menu item from drawer, use Array.map(...) instead of <DrawerItemList {...props} /> in custom drawer content.,
{drawerItems.map((item, index) => {
return (
<DrawerItem
label={item.drawerLabel}
onPress={() => props.navigation.navigate(item.routeName)}
/>
);
})}
and add a useEffect hook to custom drawer content like below,
let [drawerItems, setDrawerItems] = useState([]);
useEffect(() => {
let drawerItemsList = [];
for (const key in props.descriptors) {
if (props.descriptors.hasOwnProperty(key)) {
if (!key.includes('profile')) {
const element = props.descriptors[key];
element.options.routeName = key.substring(0, key.indexOf('-'));
drawerItemsList.push(element.options);
}
}
}
setDrawerItems(drawerItemsList);
}, []);
Another approach.,
Create an Array like below in the custom drawer content.,
const drawerItemsList = [
{
drawerLabel: 'Products',
drawerIcon: 'product',
routeName: 'products',
active: true,
},
{
drawerLabel: 'Orders',
drawerIcon: 'order',
routeName: 'orders',
active: false,
},
];
let [drawerItems, setDrawerItems] = useState(drawerItemsList);
and instead of <DrawerItemList {...props} /> use <Flatlist /> like below.,
<View>
<FlatList
data={drawerItems}
keyExtractor={(item)=>item.routeName.trim()}
renderItem={({item,index})=>(
<DrawerItem
label={item.drawerLabel}
icon={({color, size}) => <Ionicons name={item.drawerIcon} color={item.active?'#1e90ff':'#ccc'} size={size} />}
labelStyle={[item.active?{color: '#1e90ff'}:{color: '#ccc'}]}
style={item.active?{backgroundColor: '#1e90ff20'}:null}
onPress={() => {
drawerItemsList.forEach((element,i) => {
i!==index?element.active=false:element.active=true
});
setDrawerItems(drawerItemsList)
props.navigation.navigate(item.routeName)
}}
/>
)}
/>
</View>