Error in uploading image with 'react-native-image-picker' library - react-native

I am creating an android application and I need to use the react-native-image-picker library but it is showing some error, the error is:
[Unhandled promise rejection: TypeError: null is not an object (evaluating '_reactNative.NativeModules.ImagePickerManager.launchImageLibrary')]
I have tried everything like changing to different versions as well, also I have used expo-image-picker which does not show an error while fetching an image from android but gives an error when uploading it to firebase.
Please help, I have been frustrated with this error.
import {
View,
Text,
Image,
StyleSheet,
KeyboardAvoidingView,
TouchableOpacity,
ActivityIndicator
} from "react-native";
import React, { useState } from "react";
import { TextInput, Button } from "react-native-paper";
import ImagePicker, { launchImageLibrary } from "react-native-image-picker";
import storage from "#react-native-firebase/storage";
import auth from '#react-native-firebase/auth';
import firestore, {getStorage, ref, uploadBytes} from '#react-native-firebase/firestore';
export default function SignUp({ navigation }) {
const [name, setName] = useState("");
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [image, setImage] = useState(null);
const [shownext, setShownext] = useState(false);
const [loading, setLoading] = useState(false);
if (loading) {
return <ActivityIndicator size='large' />
}
const userSignUp = async () => {
setLoading(true)
if (!email || !password || !image || !name) {
alert('fill all details correctly')
return false;
}
try {
const result = await auth().createUserWithEmailAndPassword(email, password);
firestore().collection('users').doc(result.user.uid).set({
name: name,
email: result.user.email,
uid: result.user.uid,
pic:image
})
setLoading(false)
}catch (err) {
alert('something went wrong from your side')
}
}
const pickImageAndUpload = () => {
console.log(1);
launchImageLibrary({ puality: 0.5 }, async (fileobj) => {
console.log(2);
console.log(fileobj);
const uploadTask = storage().ref().child(`/userprofilepic/${Date.now()}`).putFile(fileobj.uri);
uploadTask.on(
"state_changed",
(snapshot) => {
const progress =
(snapshot.bytesTransferred / snapshot.totalBytes) * 100;
if (progress == 100) alert("image uploaded");
},
(error) => {
alert("error uploading image");
},
() => {
getDownloadURL(uploadTask.snapshot.ref).then((downloadURL) => {
setImage(downloadURL);
});
}
);});
};
return (
<KeyboardAvoidingView behavior="position" style={{ alignItems: "center" }}>
<View style={styles.box1}>
<Text style={styles.text}>Welcome to chatapplication</Text>
<Image style={styles.img} source={require("../assets/wa-logo.png")} />
</View>
{!shownext && (
<>
<TextInput
style={{ width: 330, marginTop: 50, marginBottom: 30 }}
label="Email"
value={email}
mode="outlined"
onChangeText={(text) => setEmail(text)}
/>
<TextInput
style={{ width: 330, marginBottom: 30 }}
label="Password"
value={password}
mode="outlined"
onChangeText={(text) => setPassword(text)}
secureTextEntry
/>
</>
)}
{shownext ? (
<>
<TextInput
style={{ width: 330, marginTop: 50, marginBottom: 30 }}
label="Name"
value={name}
mode="outlined"
onChangeText={(text) => setName(text)}
/>
<Button
style={{ marginBottom: 30 }}
mode="contained"
onPress={() => { pickImageAndUpload() }}
>
Upload Profile Pic
</Button>
<Button
disabled={image?false:true}
mode="contained"
onPress={() => { userSignUp() }}>
SignUp
</Button>
</>
) : (
<Button
// disabled={email&&password?false:true}
mode="contained"
onPress={() => {
setShownext(true);
}}
>
Next
</Button>
)}
<TouchableOpacity onPress={() => navigation.goBack()}>
<Text style={{ margin: 10, textAlign: "center", fontSize: 18 }}>
Already have an account?
</Text>
</TouchableOpacity>
</KeyboardAvoidingView>
);
}
const styles = StyleSheet.create({
text: {
fontSize: 22,
color: "green",
margin: 20,
},
img: {
width: 200,
height: 200,
},
box1: {
alignItems: "center",
},
});

Related

React Native: Camera from "expo-camera" stop running when face is not ever detected

I am newer for using react-native, and wanna try to create a camera with filter. I'm blocked in step to recognize face. Have success to draw rectangle when face detected, but the problem is once it goes out of detection. The camera stop running as it fixes on the last real-time capture
Here is my code:
import { useState, useEffect, useRef } from 'react'
import { Camera } from 'expo-camera'
import * as MediaLibrary from 'expo-media-library'
import { Text, StyleSheet, View, TouchableOpacity } from 'react-native'
import Button from './Button'
import { Ionicons } from '#expo/vector-icons'
import * as FaceDetector from 'expo-face-detector'
export default function PCamera() {
const cameraRef = useRef(undefined)
const [faceDetected, setFaceDetected] = useState([])
const [lastImage, setImage] = useState(undefined)
const [hasUsePermssion, setUsePermission] = useState(false)
const [type, switchToType] = useState(Camera.Constants.Type.front)
const takePicture = async () => {
if (cameraRef) {
try {
const options = {
quality: 1,
base64: true,
exif: false,
}
const data = await cameraRef.current.takePictureAsync(options)
setImage(data.uri)
console.log(data)
} catch (err) {
console.error(err)
}
}
}
const swithMode = () => {
switchToType(
type === Camera.Constants.Type.front
? Camera.Constants.Type.back
: Camera.Constants.Type.front
)
}
const handleFacesDetected = ({ faces }) => {
setFaceDetected(faces)
}
useEffect(() => {
;(async () => {
const { status } = await Camera.requestCameraPermissionsAsync()
if (status === 'granted') {
setUsePermission(true)
}
})()
}, [])
if (hasUsePermssion === null) {
return <View />
}
if (hasUsePermssion === false) {
return <Text>No access to camera</Text>
}
return (
<View style={styles.cameraContainer}>
<View style={styles.overlay}>
<Camera
ref={cameraRef}
style={styles.camera}
type={type}
onFacesDetected={handleFacesDetected}
faceDetectorSettings={{
mode: FaceDetector.FaceDetectorMode.fast,
detectLandmarks: FaceDetector.FaceDetectorLandmarks.all,
runClassifications:
FaceDetector.FaceDetectorClassifications.none,
minDetectionInterval: 100,
tracking: true,
}}
>
{faceDetected.length > 0 &&
faceDetected.map((face) => (
<View
key={face.faceID}
style={{
position: 'absolute',
borderWidth: 2,
borderColor: 'red',
left: face.bounds.origin.x,
top: face.bounds.origin.y,
width: face.bounds.size.width,
height: face.bounds.size.height,
}}
/>
))}
</Camera>
</View>
<View style={styles.optionsContainer}>
<View>
<TouchableOpacity onPress={swithMode}>
<Text>
<Ionicons
name="camera-reverse-outline"
size={24}
color="black"
/>
</Text>
</TouchableOpacity>
</View>
<Button
icon="camera"
title="Take Photo"
onPress={takePicture}
style={styles.button}
/>
<View>
<Text>...</Text>
</View>
</View>
</View>
)}
const styles = StyleSheet.create({
cameraContainer: {flex: 1,
},
overlay: {
flex: 6,
borderBottomStartRadius: 75,
borderBottomEndRadius: 75,
overflow: 'hidden',
},
camera: {
flex: 1,
},
optionsContainer: {
flex: 1,
flexDirection: 'row',
justifyContent: 'space-around',
alignItems: 'center',
},
})
N.B: Don't take care of the Button, it's a custom component and works well

Lodesh Filter is giving mid string data

I am new with React Native and facing issue with Lodesh Filter. It is giving mid-string data. Ex if I want to search Mitsubishi and start typing "mi" it will not give me mitsubishi but if I start type "sub" then it is giving me mitsubishi.
Below is my code:
import React, { useEffect, useState } from 'react';
import {View, Text, Button, TextInput, FlatList, ActivityIndicator, StyleSheet, Image} from 'react-native';
import filter from 'lodash.filter';
const CarList = () => {
const [isLoading, setIsLoading] = useState(false);
const [data, setData] = useState([]);
const [error, setError] = useState(null);
const [query, setQuery] = useState('');
const [fullData, setFullData] = useState([]);
useEffect(() => {
setIsLoading(true);
fetch(`https://myfakeapi.com/api/cars/?seed=1&page=1&results=20`)
.then(response => response.json())
.then(response => {
setData(response.cars);
setFullData(response.cars);
setIsLoading(false);
})
.catch(err => {
setIsLoading(false);
setError(err);
});
}, []);
if (isLoading) {
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<ActivityIndicator size="large" color="#5500dc" />
</View>
);
}
if (error) {
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<Text style={{ fontSize: 18}}>
Error fetching data... Check your network connection!
</Text>
</View>
);
}
const handleSearch = text => {
const formattedQuery = text.toLowerCase();
const filteredData = filter(fullData, user => {
console.log(contains(user, formattedQuery));
return contains(user, formattedQuery);
});
setData(filteredData);
setQuery(text);
};
const contains = ({ car, car_model,car_color }, query) => {
if (car.includes(query) || car_model.includes(query) || car_color.includes(query)) {
return true;
}
return false;
};
function renderHeader() {
return (
<View
style={{
backgroundColor: '#fff',
padding: 10,
marginVertical: 10,
borderRadius: 20
}}
>
<TextInput
autoCapitalize="none"
autoCorrect={false}
clearButtonMode="always"
value={query}
onChangeText={queryText => handleSearch(queryText)}
placeholder="Search"
style={{ backgroundColor: '#fff', paddingHorizontal: 20 }}
/>
</View>
);
}
return (
<View style={styles.container}>
<Text style={styles.text}>Favorite Contacts</Text>
<FlatList
ListHeaderComponent={renderHeader}
data={data}
keyExtractor={({ id }) => id}
renderItem={({ item }) => (
<View style={styles.listItem}>
<Image
source={{
uri: 'https://picsum.photos/200',
}}
style={styles.coverImage}
/>
<View style={styles.metaInfo}>
<Text style={styles.title}>{`${item.car} ${
item.car_model
}`}</Text>
</View>
</View>
)}
/>
</View>
);
}
Each car record have following fields:
{
"id": 1,
"car": "Mitsubishi",
"car_model": "Montero",
"car_color": "Yellow",
"car_model_year": 2002,
"car_vin": "SAJWJ0FF3F8321657",
"price": "$2814.46",
"availability": false
}
When you write mit, in contain function you are checking if(car.includes(text)...) but car name starts with an uppercase letter. You need to convert the car name in lowerCase before checking the text like this:
const contains = ({ car, car_model, car_color }, query) => {
if (car.toLowerCase().includes(query) || car_model.toLowerCase().includes(query) || car_color.toLowerCase().includes(query)) {
return true;
}
return false;
};

How to put the bottomsheet to the front of the screen?

In ReactNative, the bottomsheet is displayed overlaid on the fragment.
Is there a way to make the bottomsheet rise to the top of the screenenter image description here
The bottom sheet looks opaque as in the picture, so the bottom sheet cannot be touched Please help
The code below is a shortened version
enter image description here
enter image description here
import React, { FC , Component, useState, useEffect, Fragment,useCallback, useMemo, useRef } from "react"
import { FlatList, ViewStyle, StyleSheet, View, Platform, TextInput, TouchableOpacity} from "react-native"
import {
BottomSheetModal,
BottomSheetModalProvider,
BottomSheetBackdrop,
} from '#gorhom/bottom-sheet';
const ROOT: ViewStyle = {
backgroundColor: DefaultTheme.colors.background,
flex: 1,
}
export const ChecklookupScreen: FC<StackScreenProps<NavigatorParamList, "checklookup">> = observer(function ChecklookupScreen() {
const bottomSheetModalRef = useRef<BottomSheetModal>(null);
// variables
const snapPoints = useMemo(() => ['25%', '50%'], []);
// callbacks
const handlePresentModalPress = useCallback((index: string) => {
LOG.info('handlePresentModalPress', index);
bottomSheetModalRef.current?.present();
}, []);
const handleSheetChanges = useCallback((index: number) => {
LOG.info
console.log('handleSheetChanges', index);
}, []);
const renderItem = ({ item, index }) => (
<TouchableOpacity
key={index + item.inspNo + item.spvsNo}
//style={listContainer}
onPress={throttle(() => {
onClickItem(item.inspNo,item.spvsNo);
})}
>
<View>
<Fragment>
</View>
<Button icon="magnify-expand"
mode="elevated"
style={styles.detailButton}
onPress={throttle(() => {
onClickItem(item.inspNo,item.spvsNo);
})}
// onPress={() => navigation.navigate("checkdetail")}
>
</Button>
</View>
</Fragment>
</View>
</TouchableOpacity>
);
const fetchChecklookups = async (offset: number) => {
LOG.debug('fetchChecklookups:' + offset);
setRefreshing(true);
await checklookupStore.getChecklookups(offset)
setRefreshing(false);
};
const onEndReached = () => {
if (checklookupStore?.checklookupsTotalRecord <= checklookups?.length) {
LOG.debug('onEndReached555555555');
} else {
setPage(page + 1)
fetchChecklookups(page + 1);
}
};
const [searchQuery, setSearchQuery] = React.useState('');
const onChangeSearch = query => setSearchQuery(query);
return (
<Screen preset="fixed" style={{ backgroundColor: colors.background, flex: 1, padding: 10,}}>
<View style={{ flex: 1,}}>
<View style={{ flex: 1, }}>
<Searchbar
placeholder="조회조건을 입력해주세요"
onChangeText={onChangeSearch}
value={searchQuery}
onPressIn={() => handlePresentModalPress('touch on')}
/>
<BottomSheetModalProvider>
<BottomSheetModal
backgroundStyle={{ backgroundColor: "gray" }}
style={styles.bottomSheet}
ref={bottomSheetModalRef}
index={1}
snapPoints={snapPoints}
onChange={handleSheetChanges}
>
<View style={{ marginTop: 10, marginLeft: 50, marginRight: 50, flexDirection: "row"}}>
<View style={{ flex: 1, }}>
<Button
mode="outlined"
>소속을 입력하세요
</Button>
</View>
</View>
</BottomSheetModal>
</BottomSheetModalProvider>
</Screen>
)
})
You can try with portal, wrap you bottom sheet to from another package.

How to Open left side drawer and right side drawer in react native project

I wrote the below code to make multiple side drawer but unluckily I am not able.
Here open the left side drawer easily but the right-side drawer is not open. for Analyze purpose header.js file when I used here onPress={() => navigation.openDrawer()} then open left side drawer and I also used in second drawer element onPress={() => navigation.openDrawer()} also open left ride drawer but I want to open right side drawer.
What should I do?
app.js file:
import * as React from 'react';
import {View, Button,StyleSheet, Alert, Text, ActivityIndicator, Image} from 'react-native';
import {NavigationContainer} from '#react-navigation/native';
import {createStackNavigator} from '#react-navigation/stack';
import {createDrawerNavigator} from '#react-navigation/drawer';
import DrawerContent from './screens/common/DrawerContent';
import SearchDrawer from './screens/common/SearchDrawer';
import Registration from './screens/authentication/Registration';
import Login from './screens/authentication/Login';
import ForgotPassword from './screens/authentication/ForgotPassword';
import ChangePassword from './screens/authentication/ChangePassword';
import Dashboard from './screens/user/Dashboard';
import Notifications from './screens/user/Notifications';
import ProfileStep from './screens/user';
import Shipment from './screens/user/shipment';
// import SplashScreen from 'react-native-splash-screen';
// import {LogBox} from 'react-native';
import {Provider} from 'react-redux';
import AsyncStorage from '#react-native-community/async-storage';
import {store, getAsyncStorage} from './redux/store';
import messaging from '#react-native-firebase/messaging';
const Stack = createStackNavigator();
const DrawerR = createDrawerNavigator();
const DrawerL = createDrawerNavigator();
function User(props) {
const [userInfo, setUserInfo] = React.useState('');
React.useEffect(() => {
getUserInfo();
}, []);
const getUserInfo = async () => {
let userInfo = await AsyncStorage.getItem('userInfo');
if (userInfo) {
store.dispatch(getAsyncStorage());
userInfo = JSON.parse(userInfo);
setUserInfo(userInfo);
}
};
return (
<DrawerL.Navigator
drawerContent={(props) => (
<DrawerContent {...props} size="22" data={userInfo} />
)}
// drawerPosition="right"
// drawerContent={(props) => (
// <SearchDrawer {...props} size="22" />
// )}
>
{props.route.params !== undefined && props.route.params.completed ? (
<>
<DrawerL.Screen name="Dashboard" component={Dashboard} />
<DrawerL.Screen name="ProfileStep" component={ProfileStep} />
</>
) : (
<>
<DrawerL.Screen name="ProfileStep" component={ProfileStep} />
<DrawerL.Screen name="Dashboard" component={Dashboard} />
</>
)}
<DrawerL.Screen name="Shipment" component={Shipment} />
</DrawerL.Navigator>
);
}
function User1(props){
const [userInfo1, setUserInfo1] = React.useState('')
React.useEffect(() => {
getUserInfo1();
}, []);
const getUserInfo1 = async () => {
let userInfo1 = await AsyncStorage.getItem('userInfo');
if (userInfo1) {
store.dispatch(getAsyncStorage());
userInfo1 = JSON.parse(userInfo1);
setUserInfo1(userInfo1);
}
};
return (
<DrawerR.Navigator
drawerPosition="right"
drawerContent={(props) => (
<SearchDrawer {...props} size="22" data={userInfo1}/>
)}
>
</DrawerR.Navigator>
);
}
function App() {
React.useEffect(() => {
const unsubscribe = messaging().onMessage(async (remoteMessage) => {
Alert.alert('A new FCM message arrived!', JSON.stringify(remoteMessage));
});
return unsubscribe;
}, []);
return (
<Provider store={store}>
<NavigationContainer>
<Stack.Navigator
screenOptions={{
headerShown: false,
}}>
<Stack.Screen name="Login" component={Login} />
<Stack.Screen name="Registration" component={Registration} />
<Stack.Screen name="ForgotPassword" component={ForgotPassword} />
<Stack.Screen name="ChangePassword" component={ChangePassword} />
<Stack.Screen name="User" component={User} />
<Stack.Screen name="User1" component={User1} />
<Stack.Screen name="Notifications" component={Notifications} />
</Stack.Navigator>
</NavigationContainer>
</Provider>
);
}
export default App;
DrawerContent.js
import React,{useEffect} from 'react';
import {View, StyleSheet, Alert, Text, ActivityIndicator, Image} from 'react-native';
import {
Avatar,
Title,
Caption,
Drawer,
TouchableRipple,
Divider,
Switch,
} from 'react-native-paper';
import {DrawerContentScrollView, DrawerItem} from '#react-navigation/drawer';
import AsyncStorage from '#react-native-community/async-storage';
import {connect} from 'react-redux';
import Icon from 'react-native-vector-icons/MaterialCommunityIcons';
import {setTheme} from './../../redux/actions/config';
import {getThemeColors} from '../../global/themes';
import {API_URL} from './../../global/config';
import { Linking } from 'react-native';
// import {bindActionCreators} from 'redux';
var pkg = require('./../../package.json');
function DrawerContent(props) {
const [loading, setLoading] = React.useState(false);
const [profileStatus, setProfileStatus] = React.useState({});
const [whitelabel, setIfWhiteLabel] = React.useState('')
// const [isDarkMode, setIsDarkMode] = React.useState(false);
let userInfo = props.data;
const logout = () => {
Alert.alert(
'Are you sure?',
'You want to Logout',
[
{
text: 'Cancel',
style: 'cancel',
},
{
text: 'Yes',
onPress: () => {
setLoading(true);
console.log(`${API_URL}disableDevice`);
fetch(`${API_URL}disableDevice`, {
method: 'post',
body: JSON.stringify({user_id: userInfo.id}),
})
.then((res) => res.json())
.then(async (res) => {
if (!res.status) {
setLoading(false);
alert('something went wrong!!');
} else {
try {
await AsyncStorage.removeItem('userInfo');
await AsyncStorage.removeItem('profileStatus');
props.navigation.reset({
index: 0,
routes: [{name: 'Login'}],
});
} catch (exception) {
setLoading(false);
return false;
}
}
})
.catch((e) => {
setLoading(false);
console.log(e);
});
},
},
],
{cancelable: false},
);
};
const onThemeChange = async () => {
AsyncStorage.setItem(
'themeMode',
props.theme === 'default' ? 'dark' : 'default',
);
props.onSelectTheme(props.theme === 'default' ? 'dark' : 'default');
fetch(`${API_URL}toggleDarkMode`, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
user_id: userInfo.id,
dark_mode: props.theme === 'default' ? 1 : 0,
}),
})
.then((res) => res.json())
.then((res) => {
console.log(res);
})
.catch((err) => {
console.log(err);
});
};
const {colors} = props;
React.useEffect(() => {
var profileStatus = props.profileStatus;
if (profileStatus) {
profileStatus = JSON.parse(profileStatus);
setProfileStatus(profileStatus);
}
checkIfWhiteLabel()
}, [props.profileStatus]);
useEffect(() => {
checkIfWhiteLabel()
}, [])
const checkIfWhiteLabel = async () =>{
let iftru = await AsyncStorage.getItem('whiteLabel');
if(iftru == null){
setIfWhiteLabel('false')
}else{
setIfWhiteLabel(iftru)
}
}
return (
<>
<View style={{flex: 1, backgroundColor: colors.drawerBackground}}>
<DrawerContentScrollView {...props}>
<View style={styles.drawerContent}>
<View style={styles.tinyLogoDiv}>
<Image
style={styles.tinyLogo}
source={require('../../assets/logo.png')}
/>
</View>
<TouchableRipple
style={styles.userInfoSection}
onPress={() =>
props.navigation.navigate('ProfileStep', {status: 'TRUE'})
}
rippleColor="rgba(0, 0, 0, .32)">
<View style={{flexDirection: 'row'}}>
<Avatar.Image
source={require('../../assets/avater.png')}
size={50}
/>
<View style={{marginLeft: 15, flexDirection: 'column'}}>
<Title style={styles.title(colors.textColor)}>
{profileStatus.username ?? userInfo.name}
</Title>
<Caption style={styles.caption(colors.textColor)}>
{profileStatus.email ?? userInfo.email}
</Caption>
</View>
<View
style={{
justifyContent: 'center',
marginLeft: 'auto',
paddingRight: 7,
}}>
<Icon
name="account-edit"
size={25}
color={colors.textColor}
/>
</View>
</View>
</TouchableRipple>
<Divider />
<Drawer.Section style={styles.drawerSection}>
<DrawerItem
icon={() => (
<Icon name="home" size={30} color={colors.textColor} />
)}
labelStyle={{color: colors.textColor}}
label="Home"
onPress={() => {
if (profileStatus.type || profileStatus.type === undefined) {
alert('Complete Your profile first');
} else {
props.navigation.navigate('Dashboard');
}
}}
/>
<DrawerItem
icon={() => (
<Icon
name="text-box-plus"
size={30}
color={colors.textColor}
/>
)}
label="Parcel"
labelStyle={{color: colors.textColor}}
onPress={() => {
if (profileStatus.type || profileStatus.type === undefined) {
alert('Complete Your profile first');
} else {
props.navigation.navigate('Shipment');
}
}}
/>
</Drawer.Section>
</View>
</DrawerContentScrollView>
<Drawer.Section style={styles.bottomDrawerSection}>
<DrawerItem
style={{paddingBottom: 0}}
icon={() =>
loading ? (
<ActivityIndicator size={30} color={colors.primaryColor} />
) : (
<Icon name="exit-to-app" size={30} color={colors.textColor} />
)
}
label={'Logout'}
labelStyle={{color: colors.textColor}}
onPress={() => logout()}
/>
</Drawer.Section>
<View
style={{
marginBottom: 5,
alignItems: 'center',
}}>
<Text style={{opacity: 0.8, color: colors.textColor}}>
V - {pkg.version}
</Text>
</View>
</View>
</>
);
}
const mapStateToProps = (state) => {
let imagePlaceholder = JSON.parse(state.brand);
if (imagePlaceholder) {
imagePlaceholder = imagePlaceholder.default.avatar;
} else {
imagePlaceholder = '';
}
var theme = getThemeColors(state.theme);
return {
theme: state.theme,
colors: theme,
profileStatus: state.profileStatus,
imagePlaceholder: imagePlaceholder,
};
// count: state.count,
};
export default connect(mapStateToProps, {
onSelectTheme: setTheme,
})(DrawerContent);
//
const styles = StyleSheet.create({
drawerContent: {
flex: 1,
},
userInfoSection: {
paddingLeft: 20,
paddingVertical: 10,
},
title: (color) => ({
fontSize: 16,
marginTop: 3,
fontWeight: 'bold',
color: color,
}),
caption: (color) => ({
fontSize: 12,
lineHeight: 14,
opacity: 0.8,
color: color,
marginLeft:-15,
}),
row: {
marginTop: 20,
flexDirection: 'row',
alignItems: 'center',
},
section: {
flexDirection: 'row',
alignItems: 'center',
marginRight: 15,
},
paragraph: {
fontWeight: 'bold',
marginRight: 3,
},
drawerSection: {
marginTop: 15,
},
bottomDrawerSection: {
// marginBottom: 15,
borderTopColor: '#ccc',
borderTopWidth: 0.2,
borderBottomColor: '#ccc',
borderBottomWidth: 0.2,
},
preference: {
flexDirection: 'row',
justifyContent: 'space-between',
paddingVertical: 12,
paddingHorizontal: 16,
},
loading: {
position: 'absolute',
left: 0,
right: 0,
top: 0,
bottom: 0,
opacity: 0.6,
justifyContent: 'center',
alignItems: 'center',
},
loadingText: {
fontSize: 20,
paddingTop: 20,
fontWeight: 'bold',
},
tinyLogoDiv:{
// width:100,
},
tinyLogo: {
width: 150,
height: 50,
// alignItems:'center',
marginLeft:70
},
});
SearchDrawer.js
import React from 'react';
import { View, StyleSheet, Text, Button,TextInput } from 'react-native';
import { DrawerContentScrollView} from '#react-navigation/drawer';
import { setTheme } from './../../redux/actions/config';
import { getThemeColors } from '../../global/themes';
import { connect } from 'react-redux';
function SearchDrawer(props) {
return (
<>
<View style={{ flex: 1, backgroundColor: '#ffffff' }}>
<DrawerContentScrollView {...props}>
<View>
<Text>This is input Field</Text>
<TextInput
label='Search here'
style={styles.input}
placeholder="Search By Order Id"
/>
<Button
onPress={() => alert('This is a button!')}
title="Info"
color="#fff"
/>
</View>
</DrawerContentScrollView>
</View>
</>
);
}
const mapStateToProps = (state) => {
let imagePlaceholder = JSON.parse(state.brand);
if (imagePlaceholder) {
imagePlaceholder = imagePlaceholder.default.avatar;
} else {
imagePlaceholder = '';
}
var theme = getThemeColors(state.theme);
return {
theme: state.theme,
colors: theme,
profileStatus: state.profileStatus,
imagePlaceholder: imagePlaceholder,
};
};
const styles = StyleSheet.create({
drawerSection: {
marginTop: 15,
},
})
export default connect(mapStateToProps, {
onSelectTheme: setTheme,
})(SearchDrawer);
Header.js
import React from 'react';
import {
// StyleSheet,
// TouchableOpacity,
// TouchableWithoutFeedback,
Text,
View, TouchableOpacity,
AppState, TextInput, StyleSheet
} from 'react-native';
import { DrawerItem } from '#react-navigation/drawer';
import { DrawerActions } from '#react-navigation/native';
import { useNavigation } from '#react-navigation/native';
import { Appbar, Badge } from 'react-native-paper';
// import {colors} from '../../global/themes';
import { FontAwesomeIcon } from '#fortawesome/react-native-fontawesome'
import { faCoffee } from '#fortawesome/free-solid-svg-icons'
import Icon from 'react-native-vector-icons/FontAwesome';
import { connect } from 'react-redux';
import { setTheme } from './../../redux/actions/config';
// import {bindActionCreators} from 'redux';
import { getThemeColors } from '../../global/themes';
// import {useState} from 'react';
import { API_URL } from '../../global/config';
import AsyncStorage from '#react-native-community/async-storage';
import Menu, { MenuItem } from 'react-native-material-menu';
import messaging from '#react-native-firebase/messaging';
import notifee, { EventType } from '#notifee/react-native';
const ContentTitle = ({ title, color }) => (
<Appbar.Content
title={
// <View style={{zIndex: 99999999}}>
<Text style={{ fontSize: 20, color: color, zIndex: 99999999 }}>
{' '}
{title}{' '}
</Text>
// </View>
}
style={{ marginLeft: -10 }}
/>
);
function Header(props) {
const navigation = useNavigation();
console.log('Pera Navigation', navigation)
const { colors } = props;
const [notificationCount, setNotificationCount] = React.useState(0);
const [showMenu, setShowMenu] = React.useState(false);
const [appState, setAppState] = React.useState(AppState.currentState);
const [actions, setActions] = React.useState([]);
const menu = React.useRef();
const getUserId = async () => {
let userInfo = await AsyncStorage.getItem('userInfo');
if (userInfo) {
userInfo = JSON.parse(userInfo);
return userInfo.id;
}
};
function getNotificationCount() {
getUserId().then((id) => {
console.log(`${API_URL}newNotification`);
fetch(`${API_URL}newNotification`, {
method: 'post',
body: JSON.stringify({ user_id: id }),
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
})
.then((res) => res.json())
.then((res) => {
if (res.status) {
setNotificationCount(res.notification_count);
}
})
.catch((e) => {
console.log(e);
});
});
}
const _handleAppStateChange = (nextAppState) => {
getNotificationCount();
setAppState(nextAppState);
};
React.useEffect(() => {
AppState.addEventListener('change', (e) => _handleAppStateChange(e));
getNotificationCount();
notifee.createChannel({
id: 'custom-sound',
name: 'System Sound',
sound: 'notification__.mp3',
});
notifee.onForegroundEvent(({ type, detail }) => {
switch (type) {
case EventType.DISMISSED:
console.log('User dismissed notification', detail.notification);
break;
case EventType.PRESS:
let count = notificationCount;
setNotificationCount(0);
// alert('0 done');
navigation.navigate('Notifications', {
count: count,
screen: ' ',
});
break;
}
});
messaging().onMessage(async (remoteMessage) => {
// console.log('ok oko k');
await notifee.displayNotification({
title: remoteMessage.notification.title,
body: remoteMessage.notification.body,
android: {
channelId: 'custom-sound',
},
});
getNotificationCount();
});
messaging().onNotificationOpenedApp((remoteMessage) => {
let count = notificationCount;
setNotificationCount(0);
navigation.navigate('Notifications', {
count: count,
screen: 'header',
});
});
}, []);
React.useEffect(() => {
if (showMenu) {
menu.current.show();
}
}, [showMenu]);
return (
<Appbar.Header style={{ backgroundColor: colors.headerColor }}>
{props.back ? (
<Appbar.BackAction
onPress={() => (props.goBack ? props.goBack() : navigation.goBack())}
/>
) : (
<Appbar.Action
icon="menu"
onPress={() => navigation.openDrawer()}
size={28}
color={colors.textColor}
style={{ paddingLeft: 3 }}
/>
)}
<TouchableOpacity style={styles.searchSection}>
<TextInput
style={styles.input}
placeholder="Search By Order Id"
onPress={() =>navigation.openDrawer()}
/>
<Icon style={styles.searchIcon} name="search" size={20} color="#000" />
</TouchableOpacity>
{/* <TouchableOpacity onPress={() => navigation.openDrawer()}>
<Icon style={{marginLeft: 10}} name='menu'/>
</TouchableOpacity> */}
{/* <Button title='open the drawer' onPress={this.props.navigation.dispatch(DrawerActions.openDrawer('drawerOpenLeft'))}></Button>
<Button title='open the drawer right' onPress={this.props.navigation.dispatch(DrawerActions.openDrawer('drawerOpenRight'))}></Button> */}
<ContentTitle title={props.title} color={colors.textColor} />
{!props.hideNotification && (
<View>
{notificationCount > 0 && (
<Badge
visible={true}
size={16}
style={{ position: 'absolute', top: 10, right: 7, zIndex: 9999 }}>
<Text style={{ fontSize: 12 }}>{notificationCount}</Text>
</Badge>
)}
<Appbar.Action
icon="bell"
onPress={() => {
let count = notificationCount;
setNotificationCount(0);
navigation.navigate('Notifications', {
count: count,
screen: 'header',
});
}}
size={28}
color={colors.textColor}
style={{ paddingLeft: 3 }}
/>
</View>
)}
{props.selected && (
<>
<Appbar.Action
icon="delete"
onPress={() => props.onDeletePress()}
size={28}
color={colors.textColor}
style={{ left: 10 }}
/>
<Menu
ref={menu}
style={{ backgroundColor: colors.secondaryColor }}
onHidden={() => {
setShowMenu(false);
}}
button={
<Appbar.Action
icon="dots-vertical"
onPress={() => {
props.onActionPress().then((res) => {
console.log(res);
// if (res.status === 'TRUE') {
setShowMenu(res.status);
setActions(res.actions);
// } else {
// setShowMenu(false);
// }
});
}}
size={28}
color={colors.textColor}
/>
}>
{actions.length > 0 &&
actions.map((item, i) => {
return (
<>
{item.statusList !== undefined && (
<>
<MenuItem style={{ height: 40 }} disabled>
<Text style={{ color: colors.textLight }}>
{item.text}
</Text>
</MenuItem>
{item.statusList.map((list) => {
return (
<MenuItem
onPress={() => {
props.onMenuPress(item.type, list.VALUE);
menu.current.hide();
}}
key={i}>
<Text style={{ color: colors.textColor }}>
{' '}
{list.LABEL}
</Text>
</MenuItem>
);
})}
</>
)}
</>
);
})}
</Menu>
</>
)}
</Appbar.Header>
);
}
const mapStateToProps = (state) => {
var theme = getThemeColors(state.theme);
return { colors: theme };
};
export default connect(mapStateToProps, {
onSelectTheme: setTheme,
})(Header);
const styles = StyleSheet.create({
searchSection: {
flex: 1,
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#fff',
},
searchIcon: {
padding: 10,
},
input: {
flex: 1,
height: 40,
padding: 10,
paddingLeft: 0,
backgroundColor: '#fff',
color: '#424242',
},
})
I don't know if I understood well but I need a little help.

Searchable flat list react native

I am trying to search items in a flatlist, whenever i type in the search bar it only take one letter and closes the keyboard and the value inside the search bar disappear,
example when i type "george" it only takes the letter g and re-render a list of names containing the letter g and delete what's inside the search bar
how can i fix this ?
import React, { useState, useEffect } from 'react';
import { ScrollView } from 'react-native';
import { View, Text, FlatList, ActivityIndicator, SafeAreaView, TouchableOpacity } from 'react-native';
import { SafeAreaProvider } from 'react-native-safe-area-context';
import { Divider, SearchBar } from 'react-native-elements'
const Item = ({ name, lastName }) => (
<View>
<Text style={{ fontSize: 17, color: '#666', marginBottom: 10 }}>Full name: {name} {lastName}</Text>
</View>);
function Clients({ navigation }) {
const [isLoading, setLoading] = useState(true);
const usersApi = 'https://reqres.in/api/users'
const [users, setUsers] = useState([]);
const [search, setSearch] = useState("");
const [masterData, setMasterData] = useState("");
const fetchJson = async (userApi) => {
const response = await fetch(userApi);
return response.json()
}
useEffect(() => {
fetchJson(usersApi)
.then((users) => {
setUsers(users.data);
setMasterData(users.data);
})
.catch((error) => (alert(error)))
.finally(() => setLoading(false));
}, []);
const itemSeparator = () => {
return (
<Divider style={{ width: "105%", marginVertical: 3, alignSelf: 'center' }} />
)
}
const renderHeader = () => {
return (
<SearchBar
placeholder="Type Here..."
lightTheme
round
onChangeText={text => searchFilterFunction(text)}
autoCorrect={false}
/>
);
};
const searchFilterFunction = text => {
setSearch(text);
const newData = masterData.filter(item => {
const itemData = `${item.first_name.toUpperCase()} ${item.last_name.toUpperCase()}`;
const textData = text.toUpperCase();
return itemData.indexOf(textData) > -1;
});
setUsers(newData);
};
const renderItem = ({ item }) => (
<TouchableOpacity style={{
flex: 1,
padding: 10
}}
onPress={() => { navigation.navigate('Client', { item: item }); }}
underlayColor='#ccc'
activeOpacity={0.1} >
<Item name={item.first_name} lastName={item.last_name} />
</TouchableOpacity>
);
console.log(search)
console.log(users)
return (
<SafeAreaProvider>
<SafeAreaView>
<Text style={{ color: '#666', margin: 15, fontSize: 20 }}>Clients actuels</Text>
<View style={{
width: '96%',
backgroundColor: 'white',
borderRadius: 5,
alignSelf: 'center',
marginTop: 20,
}}>
<View style={{ margin: 15 }}>
{isLoading ? <ActivityIndicator size="large" /> :
<FlatList
data={users}
renderItem={renderItem}
ItemSeparatorComponent={itemSeparator}
ListHeaderComponent={renderHeader}
keyExtractor={item => item.id.toString()}
value={search}
/>}
</View>
</View>
</SafeAreaView>
</SafeAreaProvider>
);
}
export default Clients;