How to search mapped list in react native - javascript

I have been finding it very difficult to search a mapped list in react native. Actually, doing that with a Flatlist would be very easy for me, but this is really giving me a headache. I hope someone will be able to help me out.
So, the code looks like this
import React, { Component, useState } from 'react';
import { Button, Animated, Share, ScrollView,
ImageBackground, StyleSheet, View} from "react-native";
import { Container, Header, Content, ListItem, Item, Input, Text, Icon, Left, Body, Right, Switch } from 'native-base';
const Auslawpart = ({ route, navigation}) => {
const {parts, hereme} = route.params;
const [search, setSearch] = useState('');
const [filteredDataSource, setFilteredDataSource] = useState(parts);
const filterSearch = (text) => {
const newData = parts.filter((part)=>{
const itemData = part.name.toUpperCase()
const textData = text.toUpperCase()
return itemData.indexOf(textData)>-1
});
setFilteredDataSource(newData);
setSearch(text);
}
return (
<Container>
<Animated.View
style={{
transform:[
{translateY:translateY }
],
elevation:4,
zIndex:100,
}}
>
<View style={{
// marginTop:Constant.statusBarHeight,
position:"absolute",
top:0,
left:0,
right:0,
bottom: 0,
height: 50,
backgroundColor:"#f0f0f0",
borderBottomWidth: 1,
borderBottomColor: '#BDC3C7',
flexDirection:"row",
justifyContent:"space-between",
elevation: 4,
}}>
<View style={{margin: 10, flex: 1 }}>
<TouchableOpacity onPress={() => navigation.goBack()}>
<Icon type="MaterialIcons" name="arrow-back" style={{ left: 10, }}
size={50} />
</TouchableOpacity>
</View>
<View style={{
justifyContent:"space-around",
margin: 4,
flex: 1,
marginLeft:0,
}}>
<Text numberOfLines={3} style={{fontSize:10,
alignSelf: 'flex-end', color:"#212F3C",
padding: 2}}>{hereme}</Text>
</View>
</View>
</Animated.View>
<Content style={{marginTop:50}}>
<Item>
<Icon type= "MaterialIcons" />
<Input placeholder="Search legal terms and maxisms"
onChangeText={(text) => filterSearch(text)}
/>
<Icon type="Octicons" name="law" />
</Item>
{parts.map((part) => (
<TouchableOpacity
key={part.name}
>
<ListItem onPress={() =>
navigation.navigate("Auslawcount", {
meaning: part.meaning,
partname: part.name})
}>
<Icon type="Octicons" name="law" />
<Body>
<Text onScroll={(e)=>{
scrollY.setValue(e.nativeEvent.contentOffset.y)
}} style={{ fontSize: 17, fontFamily: "Lato-Regular",}} key={part.name}>{part.name.toUpperCase()}</Text>
</Body>
</ListItem>
</TouchableOpacity>
))}
</Content>
</Container>
);
};
export default Auslawpart;
The data in part.name are passed from another screen to this screen. I am try to make the Input field search through the mapped part.name. can anybody please help me with a solution.

Here is an Example
snack: https://snack.expo.io/#ashwith00/bold-waffles
const data = [
{ name: 'Suleman' },
{ name: 'Sulan' },
{ name: 'Suljan' },
{ name: 'Ram' },
{ name: 'Raj' },
];
const Auslawpart = ({ route, navigation }) => {
const {} = route.params;
const [filteredDataSource, setFilteredDataSource] = useState(parts);
const filterSearch = (text) => {
if (text.length > 0) {
const newList = data.filter((part) => {
const name = part.name.toUpperCase();
const textData = text.toUpperCase();
return name.includes(textData);
});
setFilteredDataSource(newList);
} else {
setFilteredDataSource(parts);
}
};
return (
<View>
<TextInput placeholder="Enter here" onChangeText={filterSearch} />
<ScrollView>
{filteredDataSource.map((item, i) => (
<Text key={i} style={{ paddingVertical: 30 }}>
{item.name}
</Text>
))}
</ScrollView>
</View>
);
};

Related

React Context is not updating Data

I have created a React Context API, I have stored information such as first_name, hobbies, DOB etc in it. I have crated a state in the context file and a function that changes the state when called. I am using the context in SignUpForm1.js and SignUpForm2.js, I am trying to update the state of context variables when ever there is a change in the text field, but the data in the context is not updating.
UserData.js (Context)
import React from "react";
import { useState } from "react";
import {Text} from 'react-native';
import { createContext } from "react";
const SignUpContext = React.createContext({});
const UserData = (props)=>{
var state = {
pref_pronoun: "",
DOB: "",
course: "",
first_name: "",
hobby_1: "",
hobby_2: "",
hobby_3: "",
hobby_4: "",
hobby_5: "",
home_city: "",
last_name: "",
nationality: "",
student_email: "",
university: "",
}
const [userDetails , setDetails] = useState(state);
const updateFormData = (field, value) => {
setDetails({ [field]: value });
console.log(state);
};
return (
<SignUpContext.Provider value = {{state, updateFormData}}>
{props.children}
</SignUpContext.Provider>
)
}
export {SignUpContext, UserData} ;
SignUpForm1.js
import {
Image,
Text,
StyleSheet,
View,
StatusBar,
ScrollView,
RefreshControl,
} from "react-native";
import DropDown from "./DropDown";
import Input from "./Input";
import {
KeyboardAvoidingView,
TouchableWithoutFeedback,
Keyboard,
} from "react-native";
import { useCallback, useContext, useState } from "react";
import CustomButton from "./CustomButton";
import { useNavigation } from "#react-navigation/native";
import DateTimePickerModal from "react-native-modal-datetime-picker";
import { Button } from "react-native";
import { SignUpContext, UserData } from "./GlobalUtil/UserData";
const HideKeyboard = ({ children }) => (
<TouchableWithoutFeedback onPress={() => Keyboard.dismiss()}>
{children}
</TouchableWithoutFeedback>
);
function SignUpForm1() {
const [isDatePickerVisible, setDatePickerVisibility] = useState(false);
const s_context = useContext(SignUpContext);
const showDatePicker = () => {
setDatePickerVisibility(true);
};
const hideDatePicker = () => {
setDatePickerVisibility(false);
};
const navigation = useNavigation();
const NationalityData = ["Football", "Cricket", "Programmming", "Coding"];
const [refreshing, setRefreshing] = useState(false);
const onRefresh = useCallback(() => {
setRefreshing(true);
setTimeout(() => {
setRefreshing(false);
}, 2000);
}, []);
const statusBarHeight = Platform.OS === "ios" ? 50 : StatusBar.currentHeight;
return (
<KeyboardAvoidingView behavior="padding">
<HideKeyboard>
<View
style={{
height: "100%",
width: "100%",
backgroundColor: "#f1be63",
}}
>
<View
style={{ backgroundColor: "#f1be63", height: statusBarHeight }}
>
<StatusBar barStyle="dark-content" />
</View>
<ScrollView
contentContainerStyle={styles.rootContainer}
refreshControl={
<RefreshControl
refreshing={refreshing}
onRefresh={onRefresh}
/>
}
>
<Image
source={require("../assets/aeroplane.png")}
style={styles.image}
resizeMode="contain"
/>
<Text style={styles.header}>Let's get you set up</Text>
<Text style={styles.lowerHeader}>
(we promise that it won't take long)
</Text>
<View style={[styles.textFieldsContainer]}>
<View style={{ alignItems: "center" }}>
<Input
isLabel={true}
label="Preferred Pronoun"
placeholder="He/Him"
onChangeText={(text) => {
s_context.updateFormData("pref_pronoun", text);
}}
/>
<Input
isLabel={true}
label="First Name"
placeholder="Cameron"
onChangeText={(text) => {
s_context.updateFormData("first_name", text);
}}
/>
<Input
isLabel={true}
label="Last Name"
placeholder="Cox"
onChangeText={(text) => {
s_context.updateFormData("last_name", text);
}}
/>
<View
style={{
backgroundColor: "white",
width: "80%",
borderRadius: 5,
marginTop: 10,
}}
>
<Button
title="Date of Birth"
onPress={showDatePicker}
color="gray"
/>
</View>
<DateTimePickerModal
isVisible={isDatePickerVisible}
mode="date"
onConfirm={(date) => {
s_context.updateFormData('dob', date);
hideDatePicker();
}}
onCancel={hideDatePicker}
buttonTextColorIOS="white"
pickerContainerStyleIOS={{ backgroundColor: "#D89D35" }}
isDarkModeEnabled
/>
</View>
<View style={{ alignItems: "center" }}>
<DropDown
data={NationalityData}
placeholder="Nationality"
onSelect={(selectedItem, index) => {
s_context.updateFormData("nationality", selectedItem);
}}
/>
<DropDown
data={NationalityData}
placeholder="University"
onSelect={(selectedItem, index) => {
s_context.updateFormData("university", selectedItem);
}}
/>
<DropDown
data={NationalityData}
placeholder="Course"
onSelect={(selectedItem, index) => {
s_context.updateFormData("course", selectedItem);
}}
/>
<DropDown
data={NationalityData}
placeholder="HomeTown City"
onSelect={(selectedItem, index) => {
s_context.updateFormData("homeCity", selectedItem);
}}
/>
<CustomButton
isBorder={true}
title="Next"
onPress={() => {
navigation.navigate("SignUp2");
}}
/>
</View>
</View>
</ScrollView>
</View>
</HideKeyboard>
</KeyboardAvoidingView>
);
}
const styles = StyleSheet.create({
rootContainer: {
height: "125%",
justifyContent: "flex-start",
alignItems: "center",
marginTop: 24,
},
textFieldsContainer: {
width: "100%",
flex: 1,
},
image: {
width: "25%",
height: "10%",
marginTop: 24,
},
header: {
color: "white",
fontSize: 26,
fontWeight: "bold",
marginVertical: 6,
},
lowerHeader: {
color: "white",
fontSize: 12,
marginBottom: 24,
},
});
export default SignUpForm1;
SignUpForm2.js
import {
View,
Text,
TouchableWithoutFeedback,
StyleSheet,
StatusBar,
ScrollView,
} from "react-native";
import { KeyboardAvoidingView } from "react-native";
import { Avatar } from "react-native-elements";
import Input from "./Input";
import DropDown from "./DropDown";
import { Keyboard } from "react-native";
import { Platform } from "react-native";
import { useNavigation } from "#react-navigation/native";
import CustomButton from "./CustomButton";
import { useState, useContext } from "react";
import { createNewUser } from "./util/auth";
import { SignUpContext, UserData } from "./GlobalUtil/UserData";
const HideKeyboard = ({ children }) => (
<TouchableWithoutFeedback onPress={() => Keyboard.dismiss()}>
{children}
</TouchableWithoutFeedback>
);
function SignUpForm2() {
const s_context = useContext(SignUpContext);
async function FinishBtnHandler()
{
console.log("Creating New User");
console.log("Email: " + emailText.trim());
console.log("Password: " + passwordText.trim());
await createNewUser(emailText.trim(), passwordText.trim());
}
const navigation = useNavigation();
const hobbiesData = ["Football", "Cricket", "Programmming", "Coding"];
const [emailText, setEmailText] = useState("");
function handleEmailText(newText) {
console.log("Email: " + newText);
setEmailText(newText);
}
const [passwordText, setPasswordText] = useState("");
function handlePasswordText(newText) {
console.log("Password: " + newText);
setPasswordText(newText);
}
function avatarPressHandler() {
console.log("Pressed!");
}
const statusBarHeight = Platform.OS === "ios" ? 50 : StatusBar.currentHeight;
return (
<KeyboardAvoidingView behavior="padding" style={{ flex: 1 }}>
<HideKeyboard>
<ScrollView>
<View
style={{
position: "absolute",
top: 0,
left: 0,
right: 0,
zIndex: 999,
}}
>
<View
style={{
backgroundColor: "#f1be63",
height: statusBarHeight,
}}
>
<StatusBar barStyle="dark-content" />
</View>
</View>
<View style={[styles.rootContainer, { paddingBottom: 48 }]}>
<View style={styles.lowerContainer}>
<Text style={styles.primaryText}>You're almost there!</Text>
<Avatar
rounded
size={170}
containerStyle={{ alignSelf: "center", marginTop: 24 }}
//icon={{ name: "user", type: "font-awesome" }}
overlayContainerStyle={{ backgroundColor: "#f1be63" }}
source={{
uri: "https://cdn.pixabay.com/photo/2019/11/03/20/11/portrait-4599553__340.jpg",
}}
>
<Avatar.Accessory size={20} onPress={avatarPressHandler} />
</Avatar>
<Text
style={[
styles.secondaryText,
{ marginBottom: 8, marginTop: 16 },
]}
>
Express yourself & customize your avatar
</Text>
<Input
isLabel={true}
label="Student Email"
placeholder="cce22rnu#uea.ac.uk"
onChangeText={handleEmailText}
defaultValue={emailText}
/>
<Input
isLabel={true}
label="Create Password"
placeholder="iLoveyoushakila123"
onChangeText={handlePasswordText}
defaultValue={passwordText}
/>
<Input
isLabel={true}
label="Confirm Password"
placeholder="iLoveyoushakila123"
/>
<Text style={styles.secondaryText}>
Now the exciting part - select your top 5 hobbies
</Text>
<View style={{ alignItems: "center", marginTop: 16 }}>
<DropDown
data={hobbiesData}
onSelect={(selectedItem, index) => {
s_context.updateFormData("hobby_1", selectedItem);
}}
/>
<DropDown data={hobbiesData} onSelect={(selectedItem, index) => {
s_context.updateFormData("hobby_2", selectedItem);
}}/>
<DropDown data={hobbiesData} onSelect={(selectedItem, index) => {
s_context.updateFormData("hobby_3", selectedItem);
}}/>
<DropDown data={hobbiesData} onSelect={(selectedItem, index) => {
s_context.updateFormData("hobby_4", selectedItem);
}}/>
<DropDown data={hobbiesData} onSelect={(selectedItem, index) => {
s_context.updateFormData("hobby_5", selectedItem);
}}/>
<CustomButton
isBorder={true}
title="Finish"
/*onPress={()=>{navigation.navigate("ConfirmId")}}*/ onPress={
FinishBtnHandler
}
/>
</View>
</View>
</View>
</ScrollView>
</HideKeyboard>
</KeyboardAvoidingView>
);
}
const styles = StyleSheet.create({
rootContainer: {
flex: 1,
justifyContent: "flex-start",
alignItems: "center",
backgroundColor: "#f1be63",
marginTop: 48,
backgroundColor: "#f1be63",
},
lowerContainer: {
flex: 1,
width: "100%",
alignItems: "center",
},
primaryText: {
color: "white",
fontSize: 24,
fontWeight: "bold",
},
secondaryText: {
marginTop: 8,
color: "white",
fontSize: 12,
fontWeight: "bold",
},
});
export default SignUpForm2;
You need to pass your userDetails state variable to the context, not the initial state value
<SignUpContext.Provider value={{ state: userDetails, updateFormData }}>
{props.children}
</SignUpContext.Provider>
Passing the initial state object will not see any updates you make.
Also, you should use the functional updates format to dynamically set properties in your state
setDetails((prev) => ({ ...prev, [field]: value }));
Finally, console logging state is a pointless exercise that often gives unexpected results. Just don't do it
The issue is that you are using state instead of userDetails in the updateFormData function. The state variable is never updated and remains the same initial value. To fix this, you should use setDetails instead of setState in the updateFormData function.
const updateFormData = (field, value) => {
setDetails({ ...userDetails, [field]: value });
console.log(userDetails);
};
Also, you are passing state in the SignUpContext.Provider value. You should pass userDetails instead of state.
return (
<SignUpContext.Provider value={{ userDetails, updateFormData }}>
{props.children}
</SignUpContext.Provider>
);

How to save route.params with asyncstorage?

Srry if the title makes no sense. Don't know a better title.
How can I save route.params items that I pass to my second screen using AsyncStorage?
In my first screen i have a bunch of data in a FlatList that can be opened with a Modal. Inside that Modal I have a TouchableOpacity that can send the data thats inside the Modal to my second screen. The data that has been passed to the second screen is passed to a FlatList. The data in the FlatList should be saved to AsyncStorage. Tried alot of things getting this to work, but only getting warning message
undefined. Code below is the most recent progress.
Using React Navigation V5.
FIRST SCREEN
const [masterDataSource, setMasterDataSource] = useState(DataBase);
const [details, setDetails] = useState('');
<TouchableOpacity
onPress={() => {
const updated = [...masterDataSource];
updated.find(
(item) => item.id === details.id,
).selected = true;
setMasterDataSource(updated);
navigation.navigate('cart', {
screen: 'cart',
params: {
items: updated.filter((item) => item.selected),
},
});
setModalVisible(false);
}}>
<Text>Add to cart</Text>
</TouchableOpacity>
SECOND SCREEN
import React, { useEffect, useState } from 'react';
import { View, Text, FlatList, TouchableOpacity } from 'react-native';
import { useTheme } from '../Data/ThemeContext';
import AsyncStorage from '#react-native-async-storage/async-storage';
import Ionicons from 'react-native-vector-icons/Ionicons';
export default function ShoppingList({ route, navigation }) {
const [shoppingList, setShoppingList] = useState([]);
const { colors } = useTheme();
const todo = () => {
alert('Todo');
};
useEffect(() => {
restoreShoppingListAsync();
}, []);
const shoppingListAsync = () => {
const shoppingList = route.params && route.params.items;
setShoppingList(list);
storeShoppingList(list);
};
const asyncStorageKey = '#ShoppingList';
const storeShoppingListAsync = (list) => {
const stringifiedList = JSON.stringify(list);
AsyncStorage.setItem(asyncStorageKey, stringifiedList).catch((err) => {
console.warn(err);
});
};
const restoreShoppingListAsync = () => {
AsyncStorage.getItem(asyncStorageKey)
.then((stringifiedList) => {
console.log(stringifiedList);
const parsedShoppingList = JSON.parse(stringifiedList);
if (!parsedShoppingList || typeof parsedShoppingList !== 'object')
return;
setShoppingList(parsedShoppingList);
})
.then((err) => {
console.warn(err);
});
};
const RenderItem = ({ item }) => {
return (
<View>
<TouchableOpacity
style={{
marginLeft: 20,
marginRight: 20,
elevation: 3,
backgroundColor: colors.card,
borderRadius: 10,
}}>
<View style={{ margin: 10 }}>
<Text style={{ color: colors.text, fontWeight: '700' }}>
{item.name}
</Text>
<Text style={{ color: colors.text }}>{item.gluten}</Text>
<Text style={{ color: colors.text }}>{item.id}</Text>
</View>
</TouchableOpacity>
</View>
);
};
const emptyComponent = () => {
return (
<View style={{ alignItems: 'center' }}>
<Text style={{ color: colors.text }}>Listan är tom</Text>
</View>
);
};
const itemSeparatorComponent = () => {
return (
<View
style={{
margin: 3,
}}></View>
);
};
return (
<View
style={{
flex: 1,
}}>
<View
style={{
padding: 30,
backgroundColor: colors.Textinput,
elevation: 12,
}}>
<View style={{ flexDirection: 'row', justifyContent: 'space-between' }}>
<TouchableOpacity onPress={() => navigation.goBack()}>
<Ionicons name="arrow-back-outline" size={25} color="#fff" />
</TouchableOpacity>
<Text style={{ color: '#fff', fontSize: 20 }}>Inköpslista</Text>
<TouchableOpacity>
<Ionicons
name="trash-outline"
size={25}
color="#fff"
onPress={() => todo()}
/>
</TouchableOpacity>
</View>
</View>
<View style={{ flex: 1, marginTop: 30 }}>
<FlatList
data={shoppingList}
renderItem={RenderItem}
ListEmptyComponent={emptyComponent}
ItemSeparatorComponent={itemSeparatorComponent}
initialNumToRender={4}
maxToRenderPerBatch={5}
windowSize={10}
removeClippedSubviews={true}
updateCellsBatchingPeriod={100}
showsVerticalScrollIndicator={true}
contentContainerStyle={{ paddingBottom: 20 }}
/>
</View>
</View>
);
}
As you are using async storage to maintain the cart.
I would suggest an approach as below
Update the asyn storage when new items are added to or removed from the cart
Retrieve the items from the cart screen and show the items there
Before you navigate store the items like below
AsyncStorage.setItem(
'Items',
JSON.stringify(updated.filter((item) => item.selected))
).then(() => {
navigation.navigate('Cart', {
items: updated.filter((item) => item.selected),
});
});
The cart screen would be something like below
function Cart({ navigation, route }) {
const [data,setData]=useState([]);
React.useEffect(() => {
async function fetchMyAPI() {
const value = await AsyncStorage.getItem('Items');
setData(JSON.parse(value));
}
fetchMyAPI();
}, []);
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Button title="Go back" onPress={() => navigation.goBack()} />
<FlatList
data={data}
renderItem={RenderItem}
/>
</View>
);
}
Working Example
https://snack.expo.io/#guruparan/cartexample

I can't wrap a FlatList, it makes the FlatList height is over the wrapper

Hello Everyone!
I want to display my notification data inside a Modal and using a FlatList, I am using react-native-modal for the Modal component, inside a Modal I have 3 main component like header, body, and footer.
header is just a title with the bottom line of it
body is a FlatList
and footer is a just Button for clear the notification
These 3 main components I wrap again with View component and I set the maxHeight for this (View) component
The body is the main issue here because the FlatList height is over the View height that I set the maxHeight, it's hard to explain and sorry, but you can see the picture at the bottom
And the important one is that I can't use flex:1 inside a Modal it's because a module that I use (react-native-modal) if I use flex: 1 it makes FlatList disappear
Picture
enter image description here
Code of ModalNotificationShowcase.jsx
import React, {
forwardRef,
memo,
useContext,
useEffect,
useImperativeHandle,
useState,
} from 'react';
import {View, Dimensions, Pressable, FlatList} from 'react-native';
import {Divider, Button, Icon, List} from '#ui-kitten/components';
import {IconHelper, Text, Modal} from '../Helper';
import {useRealmInstance, useRealmObjects} from '../../hooks';
import moment from 'moment';
import util from '../../utils';
import ThemeContext from '../../themes/ThemeContext';
const NotificationItem = memo(props => {
const {currentTheme} = props;
const [bgColor, setBgColor] = useState(
currentTheme === 'light' ? '#EDF1F7' : '#1A2138',
);
const notif = props.data;
const realm = props.realm;
return (
<Pressable
onPressIn={() =>
setBgColor(currentTheme === 'light' ? '#E4E9F2' : '#151A30')
}
style={{
padding: 12,
marginBottom: 12,
backgroundColor: bgColor,
borderRadius: 4,
}}
onPress={props.onPress}
onPressOut={() =>
setBgColor(currentTheme === 'light' ? '#EDF1F7' : '#1A2138')
}
>
<View style={{flexDirection: 'row'}}>
<IconHelper
color={notif.name === 'reminder' ? '#FF3D71' : '#0095FF'}
name={
notif.name === 'reminder'
? 'alert-triangle-outline'
: 'info-outline'
}
style={{marginRight: 8}}
onPress={() => console.log('Pressed')}
/>
<Text size={14} style={{flex: 1, marginBottom: 4}}>
{notif.message}
</Text>
</View>
<View style={{flexDirection: 'row', alignItems: 'center'}}>
<Text size={12} hint>
{moment(notif.createdAt).fromNow()}
</Text>
<View style={{flex: 1, alignItems: 'flex-end'}}>
<IconHelper
size={20}
color='#FF3D71'
name='trash-2-outline'
underlayColor='#E4E9F2'
onPress={() => {
realm.write(() => {
realm.delete(notif);
});
}}
/>
</View>
</View>
</Pressable>
);
});
const NotificationShowcase = props => {
const realm = useRealmInstance();
const notifications = useRealmObjects('notifications');
const {theme} = useContext(ThemeContext);
return (
<View
style={{
width: Dimensions.get('window').width - 48,
maxHeight: Dimensions.get('window').height - 48,
borderRadius: 4,
}}
>
// =====
// Header
// =====
<Text size={14} bold align='center' style={{padding: 12}}>
Notifikasi
</Text>
<Divider />
// =====
// Body
// =====
<View style={{padding: 12, flexGrow: 1, overflow: 'hidden'}}>
{notifications.isEmpty() ? (
<Text
size={14}
align='center'
hint
style={{
padding: 8,
marginBottom: 12,
backgroundColor: theme === 'light' ? '#EDF1F7' : '#1A2138',
borderRadius: 4,
}}
>
Belum ada notifikasi untuk saat ini
</Text>
) : (
// ======================
// The main issue is here
// ======================
<FlatList
data={notifications}
initialNumToRender={0}
maxToRenderPerBatch={1}
updateCellsBatchingPeriod={120}
numColumns={1}
keyExtractor={item => item._id.toString()}
renderItem={items => {
const notif = items.item;
return (
<NotificationItem
data={notif}
realm={realm}
currentTheme={theme}
/>
);
}}
/>
)}
// =====
// Footer
// =====
{!notifications.isEmpty() && (
<View
style={{
justifyContent: 'center',
alignItems: 'center',
}}
>
<Button
size='small'
appearance='outline'
accessoryLeft={props => (
<Icon {...props} name='trash-2-outline' />
)}
onPress={() => {
realm.write(() => {
realm.delete(notifications);
});
}}
>
Hapus semua
</Button>
</View>
)}
</View>
</View>
);
};
const ModalNotificationShowcase = forwardRef((props, ref) => {
let Modal_ref;
useImperativeHandle(ref, () => ({
show: () => Modal_ref.show(),
hide: () => Modal_ref.hide(),
}));
return (
<Modal
backdropStyle={{backgroundColor: 'rgba(9, 44, 76, .32)'}}
onBackdropPress={() => Modal_ref.hide()}
ref={refs => (Modal_ref = refs)}
>
<NotificationShowcase
navigate={props.navigate}
onPressNotifItem={() => Modal_ref.hide()}
/>
</Modal>
);
});
export default ModalNotificationShowcase;
Updated
const NotificationShowcase = props => {
return (
<View
style={{
flex: 1,
margin: 24,
borderRadius: 4,
}}
>
...
// =====
// Body
// =====
<View style={{flex: 1}}>
// ...
</View>
</View>
);
};

New to react native, Buttons don't seem to work individually

I'm trying to get each button to activate and "switch-on" when pressed, and I've used some documentation to help me. However, now it is not switching on.
Code Adds Switches in a FlatList
The Data should look like this:
https://imgur.com/a/761PSjre
Also, feel free to judge my code to the darkest depths of hell. I'm trying to improve my code.
import React from 'react'
import {StyleSheet, View,Text, Switch, Button, Alert, ScrollView, FlatList, SafeAreaView} from 'react-native'
export default () => {
const DATA = [
{
index: 1,
title: 'Toggle Night Mode',
},
{
index: 2,
title: 'Remind me to take a break',
},
{
index: 3,
title: "Remind me when it's bedtime",
},
];
const [enabledSwitches, setEnabledSwitches] = React.useState(DATA.length);
const toggleSwitch = () => setEnabledSwitches(previousState => !previousState);
function Item({title, index}) {
return (
<View>
<Text style={styles.text}> {title} </Text>
<Switch
trackColor={{ false: "#767577", true: "#81b0ff" }}
thumbColor="#f5dd4b"
ios_backgroundColor="#3e3e3e"
value={enabledSwitches[index]}
onValueChange={() => toggleSwitch(switches => {
switches[index] = !switches[index];
return switches;
})}
/>
</View>
)
}
function Header(){
return(
<View style = {styles.header}>
<Text style={styles.headertext}>Settings</Text>
</View>
)
}
return (
<>
<View style = {styles.container}>
<FlatList
data = {DATA}
keyExtractor = {item => item.id}
renderItem = {({ item, index }) => <Item title={item.title} index={index} /> }
ListHeaderComponent = {Header()}
/>
</View>
<View>
<Button
title = "Clear Search History"
color = "#6fb6f0"
onPress = {() => Alert.alert('Food History Has Been Cleared!')}
/>
</View>
<View>
<Button
title = "Logout"
color = "#6fb6f0"
onPress = {() => Alert.alert('Successfully Logged Out!')}
/>
</View>
</>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
text: {
fontSize: 20,
fontWeight: "300"
},
headertext: {
fontSize: 30,
fontWeight: "300"
},
header:{
flex:1,
justifyContent: 'center',
alignItems: 'center',
padding: 10,
backgroundColor: '#f5f5f5'
}
})
Try this way
import React from 'react'
import {StyleSheet, View,Text, Switch, Button, Alert, ScrollView, FlatList, SafeAreaView} from 'react-native'
export default () => {
// use data set in default state
const [data, setData] = React.useState([ {index: 1,title: 'Toggle Night Mode'},...]);
function toggleSwitch(value, index){
const newData = [...data];
const newData[index].isEnable = value;
setData(newData);
}
function Item({item, index}) {
return (
<View>
<Text style={styles.text}> {item.title} </Text> // use `title` here like this
<Switch
.....
value={item.isEnable || false} // change here
onValueChange={(value) => toggleSwitch(value, index) } // change here
/>
</View>
)
}
return (
<>
<View style = {styles.container}>
<FlatList
data = {data}
keyExtractor = {item => item.id}
renderItem = {({ item, index }) => <Item item={item} index={index} /> } // send `item` as prop
/>
</View>
</>
);
}

App crashes when entering in screen React Native

I'm making a mobile app and then suddenly when I enter this Screen the whole app crashes. It was working before but, after I changed some style, it gave me some errors about too much Call Stack but stopped saying that and just crashes. I really don't know what's causing this. I tried to see if there was on the UseEffect() I think there is nothing there causing this.
import React, { useEffect, useState, useContext} from "react";
import {
View,
Text,
StatusBar,
TouchableOpacity,
ScrollView,
AsyncStorage,
Dimensions,
Image,
Alert,
} from "react-native";
import PlusImage from "../../../../assets/add_circle-24px.png";
import mainContext from "../../../services/contexts/mainContext";
import listContext from "../../../services/contexts/listContext";
import taskContext from "../../../services/contexts/taskContext";
import { MaterialIcons } from "#expo/vector-icons";
import styles from "./styles";
import TaskItem from "../../utils/TaskItem";
import Animated from "react-native-reanimated";
import { FlatList } from "react-native-gesture-handler";
export default function List({ route, navigation }) {
const {
clean,
getTasksList,
edited,
toogleEdited,
deleteList,
doneTasks,
todoTasks,
} = useContext(listContext);
const { taskEdited, idtask, deleteTask } = useContext(taskContext);
const [listName, setListName] = useState("");
const [screenTasks, setScreenTasks] = useState([{}]);
const [done, setDone] = useState(false);
const screenHeight = Math.round(Dimensions.get("window").height);
async function getListName() {
setListName(await AsyncStorage.getItem("listName"));
}
async function asyncGetTasks() {
await getTasksList();
}
useEffect(() => {
if (listName) getListName();
asyncGetTasks();
setScreenTasks(done ? doneTasks : todoTasks);
if (idtask) {
navigation.navigate("Task");
}
}, [edited, taskEdited, idtask, done]);
return (
<View style={styles.container}>
<StatusBar hidden />
<View style={styles.buttonsContainer}>
<TouchableOpacity
onPress={() => {
navigation.goBack();
clean();
}}
>
<MaterialIcons name="arrow-back" size={32} />
</TouchableOpacity>
<TouchableOpacity
onPress={() => {
Alert.alert(
"Are you sure you want to delete this list?",
"",
[
{
text: "Cancel",
style: "cancel",
},
{
text: "OK",
onPress: () => {
deleteList();
clean();
navigation.goBack();
},
},
],
{ cancelable: true }
);
}}
>
<MaterialIcons name="delete" size={32} color="#bc0000" />
</TouchableOpacity>
</View>
<View style={styles.titleContent}>
<Text style={styles.titleText}>{listName}</Text>
</View>
<View style={styles.midButtonsContainer}>
<View
style={{
opacity: 1,
backgroundColor: done ? null : "#dddddd",
borderRadius: 7,
padding: 8,
opacity: 1,
}}
>
<TouchableOpacity
onPress={() => {
setDone(false);
toogleEdited();
}}
>
<Text>To do</Text>
</TouchableOpacity>
</View>
<View
style={{
opacity: 1,
backgroundColor: done ? "#dddddd" : null,
borderRadius: 7,
padding: 8,
opacity: 1,
}}
>
<TouchableOpacity
onPress={() => {
setDone(true);
toogleEdited();
}}
>
<Text style={styles.doneButton}>Done</Text>
</TouchableOpacity>
</View>
</View>
{screenTasks.length > 0 ? (
<FlatList
data={screenTasks}
renderItem={(item, index) => {
return (
<TaskItem
OnSwipeRight={() => deleteTask(item.item._id)}
{...{ item }}
/>
);
}}
/>
) : (
<View style={styles.emptyContent}>
<Text style={styles.emptyText}>This list don't have tasks yet</Text>
</View>
)}
<TouchableOpacity
style={{
position: "absolute",
top: screenHeight - 120,
right: 28,
flexDirection: "row",
width: 50,
alignSelf: "flex-end",
}}
onPress={() => {
navigation.navigate("NewTask");
}}
>
<Image source={PlusImage} />
</TouchableOpacity>
</View>
);
}
Have you tried to import it from the react lib?
import React, { useEffect } from 'react';
I don't see it in your import above.

Categories

Resources