react native `TouchableOpacity` in 'absolute' view can not be clickable on android - expo

I'v try to make a SlectBox with react native.
To make that dropdown menu can be floated, I gava an absolute position to wrapper View, then make a clickable component with TouchableOpacity inside that View. It works well on Ios and Web, but not on android. There were many solutions on google like reordering component or give a zIndex to WrapperView or use Pressable etc.., but I could not find proper solution for my case.
Belows are my whole code. and You can test this code here.
Thank you in advance.
import {
Animated,
Easing,
Platform,
StyleProp,
TextStyle,
TouchableOpacity,
View,
ViewStyle,
} from 'react-native';
import {DoobooTheme, light, useTheme} from '../theme';
import React, {FC, ReactElement, useEffect, useRef, useState} from 'react';
import {Icon} from '../Icon';
import {Typography} from '../Typography';
import styled from '#emotion/native';
import {withTheme} from '#emotion/react';
const Title = styled.View`
width: 200px;
height: 30px;
border-width: 1px;
flex-direction: row;
justify-content: center;
align-items: center;
`;
const Item = styled.View`
height: 30px;
width: 200px;
border-bottom-width: 1px;
border-left-width: 1px;
border-right-width: 1px;
justify-content: center;
align-items: center;
`;
type Styles = {
titleContainer?: StyleProp<ViewStyle>;
titleText?: StyleProp<TextStyle>;
rightElementContainer?: StyleProp<ViewStyle>;
itemContainer?: StyleProp<ViewStyle>;
itemText?: StyleProp<TextStyle>;
};
interface ItemCompProps {
value: string;
order: number;
styles?: Styles;
setIsOpened: (value: boolean) => void;
itemActiveOpacity: number;
onPress?: (i: number) => void;
}
const ItemComp: FC<ItemCompProps> = ({
value,
order,
styles,
setIsOpened,
itemActiveOpacity,
onPress,
}) => {
const {theme} = useTheme();
const handlePress = (): void => {
onPress?.(order);
setIsOpened(false);
};
return (
<TouchableOpacity onPress={handlePress} activeOpacity={itemActiveOpacity}>
<Item
style={[
{
borderColor: theme.primary,
backgroundColor: theme.textContrast,
},
styles?.itemContainer,
]}>
<Typography.Body2 style={styles?.itemText}>{value}</Typography.Body2>
</Item>
</TouchableOpacity>
);
};
interface Props {
data: string[];
onPress?: (i: number) => void;
selectedIndex?: number;
theme?: DoobooTheme;
style?: StyleProp<ViewStyle>;
styles?: Styles;
rotateDuration?: number;
titleActiveOpacity?: number;
itemActiveOpacity?: number;
isRotate?: boolean;
rightElement?: ReactElement | null;
}
const Component: FC<Props> = ({
data,
onPress,
selectedIndex = 0,
style,
styles,
rotateDuration = 200,
titleActiveOpacity = 1,
itemActiveOpacity = 1,
isRotate: shouldRotate = true,
rightElement = <Icon name="chevron-down-light" />,
}) => {
const {theme} = useTheme();
const [isOpened, setIsOpened] = useState(false);
const rotateAnimValue = useRef(new Animated.Value(0)).current;
useEffect(() => {
const toValue = isOpened ? 1 : 0;
if (!shouldRotate) rotateAnimValue.setValue(toValue);
Animated.timing(rotateAnimValue, {
toValue,
duration: rotateDuration,
easing: Easing.linear,
useNativeDriver: Platform.OS !== 'web' ? true : false,
}).start();
}, [isOpened, rotateAnimValue, rotateDuration, shouldRotate]);
return (
<View style={[style]}>
<TouchableOpacity
onPress={() => setIsOpened((prev) => !prev)}
activeOpacity={titleActiveOpacity}>
<Title
style={[
{
borderColor: theme.primary,
backgroundColor: theme.textContrast,
},
styles?.titleContainer,
]}>
<Typography.Body2 style={styles?.titleText} testID="selected-value">
{data[selectedIndex]}
</Typography.Body2>
{rightElement ? (
<Animated.View
style={[
{
position: 'absolute',
right: 10,
transform: [
{
rotate: rotateAnimValue.interpolate({
inputRange: [0, 1],
outputRange: ['0deg', '180deg'],
}),
},
],
},
styles?.rightElementContainer,
]}>
{rightElement}
</Animated.View>
) : null}
</Title>
</TouchableOpacity>
<View>
<View style={{position: 'absolute'}}>
{isOpened &&
data.map((datum, key) => (
<ItemComp
key={key}
order={key}
value={datum}
styles={styles}
setIsOpened={setIsOpened}
onPress={onPress}
itemActiveOpacity={itemActiveOpacity}
/>
))}
</View>
</View>
</View>
);
};
Component.defaultProps = {theme: light};
export const SelectBox = withTheme(Component);
My solution
I resolved this problem with react-native-gesture-handler. :)
Install react-native-gesture-handler, then using TouchableOpacity from that.

Try to render out the component you want to be on top of stack below the component you want to bring below it
How I solve this issue:
I was implementing custom dynamic toaster using context to use it globally and wasn't able to access touchable opacity due to absolute positioning but i realized i was rendering my Toaster component before my main Stack Navigator which was bringing my toaster below navigation layer so i rendered it after stack navigator and it worked
BEFORE:
<ToasterContext.Provider value={{toasts:this.state.toastState, showToaster: this.showToaster,closeToaster: this.closeToaster }}>
<Provider store={store.store}>
<PersistGate loading={null} persistor={store.persistor}>
{toastState.length > 0
&& toastState.length <= 3
&& toastState.map((t, i) => {
return(
<DynamicToast i={i} key={i} t={t} position={"bottom"} duration={4000} closeToaster={this.closeToaster} />
)
}
)}
<NetworkConnectionModal/>
<AppContainer /> // I was rendering before my AppContainer
</PersistGate>
</Provider>
</ToasterContext.Provider>
AFTER: (Resolved my problem)
<ToasterContext.Provider value={{toasts:this.state.toastState, showToaster: this.showToaster,closeToaster: this.closeToaster }}>
<Provider store={store.store}>
<PersistGate loading={null} persistor={store.persistor}>
<NetworkConnectionModal/>
<AppContainer />
{toastState.length > 0
&& toastState.length <= 3
&& toastState.map((t, i) => {
return(
<DynamicToast i={i} key={i} t={t} position={"bottom"} duration={4000} closeToaster={this.closeToaster} />
)
}
)}
</PersistGate>
</Provider>
</ToasterContext.Provider>

Most of this is because the element is hidden behind other elements after absolute positioning.
Just like the picture in PPT is set to the bottom, but in some cases in HTML, you can still see your element. In this case, we need to set this element to the top.
Open the developer tool, select your element, add a Z-index to the element style of this element, and increase from 2 to see which value can just select your element. After confirmation, add a style to the project file.
z-index: 2,//add this to your component style

Related

possible unhandled promise rejection_Expo Image Picker

I want to use Expo Image Picker, but I'm getting the following error.
'Console Warning : possible unhandled promise rejection (id : 0)'.
I already installed 'expo-image-picker'.
Here's the promise code, I don't see what's wrong here, any ideas?
import { StatusBar } from 'expo-status-bar';
import React, { useState, useEffect } from 'react';
import { Platform, StyleSheet, Text, View, Button,Image } from 'react-native';
import * as ImagePicker from 'expo-image-picker';
import Constants from 'expo-constants';
export default function App() {
const [image,setImage] = useState(null);
useEffect(async () => {
if(Platform.OS !== 'web'){
const {status} = await ImagePicker.requestMediaLibraryPermissionsAsync();
if (status !== 'granted'){
alert('Permisson denied!')
}
}
}, []);
const PickImage = async() => {
let result = await ImagePicker.launchImageLibraryAsync({
mediaTypes : ImagePicker.mediaTypesOptions.All,
allowsEditing:true,
aspect:[4,3],
quality:1
})
console.log(result)
if(!result.cancelled ){
setImage(result.uri)
}
}
return (
<View style={styles.container}>
<Button title = "Choose Image" onPress = {PickImage}/>
{image && <Image source={{uri:image}} style = {{
width : 200,
height:200
}}/>}
<StatusBar style="auto" />
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
Assigning properties to mediatypes is incorrect.
Correction: mediaTypes:ImagePicker.MediaTypeOptions.All,

Search from list in React Native

I just wanna know how can I make search function in react native. I have a very big list of text(in local js file) and also Text input space. I want to make possible when users type something they can find what they looking for from list below. Here is my code and screenshot of App. I'm new in programming so please use easy terms =) app screenshot
project datebase sample
import React from 'react';
import { SafeAreaView, View, FlatList, StyleSheet, Text, StatusBar, TextInput } from 'react-native';
import {DATA} from "../Data/AbrData";
const Item = ({ title }) => (
<View style={styles.item}>
<Text style={styles.title}>{title}</Text>
</View>
);
const SearchScreen = ({navigator}) => {
const renderItem = ({ item }) => (
<Item title={item.title} />
);
return (
<SafeAreaView style={styles.container}>
<TextInput
style={{
height: 50,
borderColor: '#919191',
borderWidth: 1,
margin: 10,
paddingLeft: 15,
borderRadius:10
}}
placeholder="Axtaris..."
/>
<FlatList
data={DATA}
renderItem={renderItem}
keyExtractor={item => item.id}
/>
</SafeAreaView>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
marginTop: StatusBar.currentHeight || 0,
marginBottom:75,
},
item: {
backgroundColor: '#ededed',
padding: 20,
marginVertical: 2,
marginHorizontal: 10,
borderRadius: 20,
},
title: {
fontSize: 20,
},
});
export default SearchScreen;
Really Fast this is what I came up with.
import React, {useState, useEffect} from 'react';
import {
SafeAreaView,
StatusBar,
StyleSheet,
Text,
View,
FlatList,
TextInput,
} from 'react-native';
const App = () => {
const DATA = [{title: 'lorumn ispum'}, {title: 'lorumn ispum'}];
const [searchText, onChangeSearch] = useState('');
const [filteredData, setFilteredData] = useState([]);
useEffect(() => {
const filtered = DATA.filter(item =>
item.title.toLowerCase().includes(searchText.toLowerCase()),
);
if (searchText === '') {
return setFilteredData(DATA);
}
setFilteredData(filtered);
}, [searchText]);
const Item = ({title}) => (
<View style={styles.item}>
<Text style={styles.title}>{title}</Text>
</View>
);
const renderItem = ({item}) => <Item title={item.title} />;
return (
<SafeAreaView style={styles.container}>
<TextInput
style={{
height: 50,
borderColor: '#919191',
borderWidth: 1,
margin: 10,
paddingLeft: 15,
borderRadius: 10,
}}
onChangeText={newText => onChangeSearch(newText)}
placeholder="Axtaris..."
/>
<FlatList
data={filteredData}
renderItem={renderItem}
keyExtractor={(item, index) => item.key}
/>
</SafeAreaView>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
marginTop: StatusBar.currentHeight || 0,
marginBottom: 75,
},
item: {
backgroundColor: '#ededed',
padding: 20,
marginVertical: 2,
marginHorizontal: 10,
borderRadius: 20,
},
title: {
fontSize: 20,
},
});
export default App;
I suggest watching this video! I learned how to simply filter a list from this video. Its plain js but the idea is the same.
https://www.youtube.com/watch?v=TlP5WIxVirU&ab_channel=WebDevSimplified
If you look at the repo of that video it boils down to the following:
searchInput.addEventListener("input", e => {
const value = e.target.value.toLowerCase()
users.forEach(user => {
const isVisible =
user.name.toLowerCase().includes(value) ||
user.email.toLowerCase().includes(value)
user.element.classList.toggle("hide", !isVisible)
})
})
Everytime the input changes (someone type something in the search field), the event listener is fired and converts the fields to lower case and compares it to the value your looking for. If the text contains the value it unhides it from the list. it does this for every entry in your dataset and thus filters the dataset to what you are looking for.

In Android Modal - wrapping content in GestureHandlerRootView not fixing react-native-gesture-handler

I am using expo ^40.0.0.
I am trying to get react-native-gesture-handler components to work in a <Modal> from react-native in Android. I followed docs here - https://docs.swmansion.com/react-native-gesture-handler/docs/#for-library-authors
It stays to wrap in <GestureHandlerRootView>, I did this but it doesn't fix the issue.
I created a snack demo of issue - https://snack.expo.io/#noitidart/frisky-carrot
Here you see a "Tapped here count: 0". Please try tapping it, you will see it doesn't increment the counter.
You will see a "RN BUTTON" this works but it is not from react-native-gesture-handler.
Here is my code from the snack:
import * as React from 'react';
import { Text, View, Modal, Button as RNButton } from 'react-native';
import {
BaseButton,
GestureHandlerRootView
} from 'react-native-gesture-handler';
export default function App() {
return (
<Modal animationType="slide" transparent={false}>
<Example />
</Modal>
);
}
const Example = function () {
const [cnt, setCnt] = React.useState(0);
return (
<View style={{ justifyContent: 'center', flex: 1 }}>
<RNButton title="rn button" onPress={() => alert('hi')} />
<GestureHandlerRootView>
<BaseButton
onPress={() => {
// alert('pressed');
setCnt(cnt + 1);
}}
>
<View style={{ backgroundColor: 'steelblue', height: 100 }}>
<Text>Tapped here count: {cnt}</Text>
</View>
</BaseButton>
</GestureHandlerRootView>
</View>
);
};

Element with fixed position on viewport in React Native Web?

I need to stick a footer component to the bottom of the viewport. The content above it is in a ScrollView. Im using React Native and React Native Web (thank you Expo) to build for both the web and native.
This works for native but not web:
export default function App() {
return (
<View style={styles.container}>
<ScrollView>
{new Array(100).fill("").map((_, index) => {
return <Text key={index}>Blah {index}</Text>;
})}
</ScrollView>
<View style={styles.footer}>
<Text>Im a footer</Text>
</View>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: "center",
},
footer: {
backgroundColor: "green",
padding: 20,
width: "100%",
},
});
I can hack it with this code. fixed is not officially supported but the CSS is applied in the web.
footer: {
// #ts-ignore
position: Platform.OS === "web" ? "fixed" : undefined,
bottom: 0,
left: 0,
}
Without the #ts-ignore I get this error from TypeScript:
  Type '"fixed"' is not assignable to type '"absolute" | "relative" | undefined'.
Is there a non-hacky way to do this?

Dollar Format Regex in React Native

I'm trying to create a method in React Native that formats my input to dollar format.
onChangeNumberFormat = (text, input) => {
const obj = { ...this.state.data };
const value = text.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, '$1,')
obj[input] = value;
this.setState({
data: obj
});
};
My input (I'm using Native Base):
<Input
value={Amount}
onChangeText={(text) => this.onChangeNumberFormat(text, 'RentalAmount')}
style={styles.valueText}
/>
When I enter 5000.00, it formats to 5,000.00 which is correct. However, if I delete the last 3 0 zeros, it becomes 5,00 instead of 500. How can I fix it? Also, is there a way to always put the '$' in the front and just accept numbers in the Input?
Thanks
To format currency you can use one of these libraries:
currency.js
dinero.js
accounting.js
wallet.js
Otherwise, you can do something like this:
const format = amount => {
return Number(amount)
.toFixed(2)
.replace(/\d(?=(\d{3})+\.)/g, '$&,');
};
Check out the demo https://snack.expo.io/#abranhe/currency-formatting
import React, { useState } from 'react';
import { Text, View, TextInput, StyleSheet } from 'react-native';
export default () => {
const [money, setMoney] = useState(0);
const format = amount => {
return Number(amount)
.toFixed(2)
.replace(/\d(?=(\d{3})+\.)/g, '$&,');
};
return (
<View style={styles.container}>
<Text style={styles.paragraph}>$ {format(money)}</Text>
<TextInput
value={money}
onChangeText={money => setMoney(money)}
style={styles.input}
/>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
},
paragraph: {
margin: 24,
fontSize: 18,
textAlign: 'center',
},
input: {
height: 30,
borderColor: 'black',
borderWidth: 1,
},
});