My app displays images and other info getting data from a JSON, and I want to set a blurRadius on the selected image when the unblur function is called.
My code is the following:
const [blur, setBlur] = useState(160);
const unblur = () => {
if(blur == 160){
setBlur(0);
}
}
{isLoading ? <ActivityIndicator/> : (
<FlatList
data={data}
keyExtractor={({ id }, index) => id}
renderItem={({ item }) => (
<>
<Text style={{ textAlign: "left", color: 'white', fontSize: 24 }}>
<Image style={{ alignSelf: "center" }} source={{uri: item.profile_picture, width: 48, height: 48}} />
{item.username}
</Text>
<TouchableOpacity onPress={() => unblur()}>
<Image style={{ alignSelf: "center" }} blurRadius={blur} source={{uri: item.picture, width: 400, height: 320}} />
</TouchableOpacity>
<Text style={{ textAlign: "left", color: 'white', fontSize: 24 }}>
ID {item.id}
</Text>
<Text>
{'\n'}{'\n'}
</Text>
</>
)}
/>
)}
I want to change the {blur} value for a given image when I tap the TouchableOpacity component of the image I want to unblur. Right in this moment when I tap an image, all the images in the list are getting unblurred.
You should add the blur values inside your items like this. Create a new components called Items. Then, add the blur state inside it. (not inside Main).
const Main = () => {
if (isLoading) {
return;
<ActivityIndicator />;
}
return (
<FlatList
data={data}
keyExtractor={({ id }, index) => id}
renderItem={({ item }) => <Item item={item} />}
/>
);
};
const Item = ({ item }) => {
const [blur, setBlur] = useState(160);
const unblur = () => {
if (blur == 160) {
setBlur(0);
}
};
return (
<>
<Text style={{ textAlign: "left", color: "white", fontSize: 24 }}>
<Image
style={{ alignSelf: "center" }}
source={{ uri: item.profile_picture, width: 48, height: 48 }}
/>
{item.username}
</Text>
<TouchableOpacity onPress={() => unblur()}>
<Image
style={{ alignSelf: "center" }}
blurRadius={blur}
source={{ uri: item.picture, width: 400, height: 320 }}
/>
</TouchableOpacity>
<Text style={{ textAlign: "left", color: "white", fontSize: 24 }}>
ID {item.id}
</Text>
<Text>
{"\n"}
{"\n"}
</Text>
</>
);
};
Also, may I suggest you can use 'onPressIn'. That way, image will unblur when the finger tap the image, not press the image. But that was your decision.
Related
My main issue with my current react native app is that when a user searches for a nft using a web3 api im using, i render a like button next to every image of the nft. I added some logic for making the like button red but when i like a NFT all the other like buttons for all the other NFT's get liked. How can i fix this to where only the specific like button that gets pressed shows that it is pressed.
code:
export const Profile = ({setLoggedIn}) => {
const [profileData, setProfileData] = useState([]);
const [apiQ,setApiQ] = useState("")
const [nfttei,setNftTei] = useState("")
const [comments,setComments] = useState([])
const[commentText,setCommentText] = useState("")
async function getData () {
const options = {method: 'GET', headers: {accept: 'application/json', 'X-API-Key': 'WYON0dXwg4zG3GSsaPb79ofaPTLAbDUpmt01OuTlZihmzoH1F059it3bdsXSou0t'}};
const data = await fetch(`https://deep-index.moralis.io/api/v2/nft/search?chain=eth&format=decimal&q=${apiQ}&filter=name&limit=10`, options)
const ddata = await data.json()
setProfileData(ddata.result)
}
async function handleNftIn () {
setApiQ(nfttei)
setNftTei("")
}
useEffect(() => {
getData();
}, [apiQ]);
function liked (id) {
setPressed(true)
}
const [pressed,setPressed] = useState(false)
return (
<View style={{padding: 20}}>
<Text style={{fontSize: 40, fontWeight: "700"}}>NFTS</Text>
<View style={{marginBottom: 20}}>
<Text style={{fontSize: 25, fontWeight: "650", marginBottom: 10}}>What kind of NFT?</Text>
<View style={{flexDirection: "row", justifyContent: "space-between", alignItems: "center"}}>
<TextInput
placeholder='type nft keyword'
style={{
backgroundColor: "#D1D1D1",
borderRadius: 20,
padding: 10,
fontSize: 16,
width: "60%"
}}
onChangeText={(val) => setNftTei(val)}
value={nfttei}
/>
<AntDesign name="rightcircle" size={30} color="#3A84EC" onPress={handleNftIn}/>
</View>
</View>
<ScrollView>
{profileData ? <>
{profileData.map((el, key,id) =>
<View style={{
backgroundColor: "#fff",
padding: 10,
borderRadius: 20,
marginBottom: 20
}} key={key}>
<View style={{position: "relative"}}>
<View style={{position: "absolute", zIndex: 10, right: 0, backgroundColor: "#fff", padding: 8,borderRadius: 30, marginRight: 20, marginTop: 10}}>
<AntDesign onPress={(id) => liked(id)} name="heart" size={24} color={pressed ? "#FF717B": "grey"} />
</View>
{JSON.parse(el.metadata).image.includes("https") ? <>
<Image source={{
uri: `${JSON.parse(el.metadata).image}`
}} style={{width: "1005", height: 200, borderRadius: 30, width: "100%"}}/>
</>: null}
</View>
<View style={{marginTop: 20}}>
<View style={{flexDirection: "row", alignItems:"center"}}>
<Text style={{marginRight:10, color: "grey"}}>ID</Text>
<View style={{width: 10,height:10,backgroundColor:"#000", borderRadius:50}}></View>
<Text style={{marginLeft: 10}}>{el.token_id}</Text>
</View>
<Text style={{fontSize: 20, fontWeight: "700", marginBottom: 10}} key={key}>{JSON.parse(el.metadata).name}</Text>
<Text>{JSON.parse(el.metadata).description}</Text>
<View style={{backgroundColor: "#000", borderRadius: 10,padding:7,justifyContent: "center", alignItems: "center"}}>
{el.token_uri.includes("https") ? <>
<A style={{color:"white", fontSize: 19}} href={el.token_uri}><Text>learn More</Text></A>
</> : <Text>Learn More</Text>}
</View>
</View>
</View>
)}
</>: <>
<Text style={{
fontWeight:"700",
color:"#000",
fontSize:20,
marginBottom:20
}}>Try searching something! Anything!</Text>
<Image source={{
uri:"https://mir-s3-cdn-cf.behance.net/project_modules/max_1200/50e513115094373.6047d1f4cf3f1.jpg"
}} style={{
width:"100%",
borderRadius:20,
height:500
}}/>
</>}
</ScrollView>
</View>
)
}
image:
what its giving me:
I am quite new to react native. I have created a FlatList for rendering this list of items, however, it is not scrolling. I've googled it for hours and tried nearly everything suggested in stack overflow threads - removed flex, added flex, wrapped it in a view, but nothing seems to work.
Here is my code (the issue is in the second FlatList) -
return(
<View style = {{ height: '100%' }}>
<View style = {{ width: '100%' }}>
<AppHeader />
</View>
<View style = {{ width: '100%'}}>
<View style = {{ width: '70%', alignSelf: 'center', flex: 1 }}>
<View>
<FlatList
data = {this.getTodayDay()}
renderItem = {this.renderItemDays}
keyExtractor = {this.keyExtractor}
/>
</View>
<FlatList
data = {this.getVisibleHours()}
renderItem = {this.renderItem}
keyExtractor = {this.keyExtractor}
scrollEnabled = {true}
/>
</View>
</View>
</View>
this.renderItem -
renderItem = () => {
// irrelevant code
if( isClass === true ){
return(
<ListItem bottomDivider = {true} style = {styles.renderItemActiveClass}>
<ListItem.Content>
<TouchableOpacity
onPress = {()=>{
this.props.navigation.navigate('ClassDetailsScreen', { "data": classData })
}}>
<ListItem.Title>{ definiteClassTime }</ListItem.Title>
<ListItem.Subtitle>{ classData.class_name }</ListItem.Subtitle>
</TouchableOpacity>
</ListItem.Content>
</ListItem>
)
}
else{
return(
<ListItem bottomDivider = {true} style = {styles.renderItemClass}
containerStyle = {styles.renderItemContent}>
<ListItem.Content>
<ListItem.Title>{item}:00</ListItem.Title>
<ListItem.Subtitle>No Class</ListItem.Subtitle>
</ListItem.Content>
</ListItem>
)
}
}
the StyleSheet -
renderItemClass: {
borderColor: 'purple',
borderWidth: 2
},
renderItemActiveClass: {
borderColor: 'green',
borderWidth: 2
},
renderItemContent: {
},
Could somebody please tell me what I'm doing wrong?
Add a height to both the flatlist. And also wrap your second flatlist within a seperate view. Here is an example:
return (
<View style={{ height: "100%" }}>
<View style={{ width: "100%" }}>
<AppHeader />
</View>
<View style={{ width: "100%" }}>
<View style={{ width: "70%", alignSelf: "center", flex: 1 }}>
<View style={{ height: 60, alignSelf: "center" }}>
<FlatList
data={this.getTodayDay()}
renderItem={this.renderItemDays}
keyExtractor={this.keyExtractor}
/>
</View>
<View style={{ height: 60, alignSelf: "center" }}>
<FlatList
data={this.getVisibleHours()}
renderItem={this.renderItem}
keyExtractor={this.keyExtractor}
scrollEnabled={true}
/>
</View>
</View>
</View>
</View>
);
How do I pass FlatList items to another screen that also have a FlatList?
I'm using React Navigation V5 to pass the FlatList item to the other screen. Thats working fine. I can see the text when only using ´<Text.>{details.id}</Text .>´ but not when trying to pass it to FlatList, then there is nothing.
CODE
import React, { useState } from 'react';
import {
View,
TextInput,
FlatList,
Text,
TouchableOpacity,
Linking,
Modal,
ScrollView,
} from 'react-native';
import { useTheme } from '../Data/ThemeContext';
import DataBase from '../Data/DataBase';
import Octicons from 'react-native-vector-icons/Octicons';
export default function Home({ navigation }) {
const [search, setSearch] = useState('');
const [masterDataSource, setMasterDataSource] = useState(DataBase);
const [modalVisible, setModalVisible] = useState(false);
const [details, setDetails] = useState('');
const { colors } = useTheme();
const filteredDataSource = masterDataSource.filter((item) => {
return (
item.name.includes(search) ||
(item.id && item.id.includes(search)) ||
(item.gluten && item.gluten.includes(search)) ||
(item.company && item.company.includes(search))
);
});
const itemSeparatorComponent = () => {
return (
<View
style={{
margin: 3,
}}></View>
);
};
const emptyComponent = () => {
return (
<View style={{ alignItems: 'center' }}>
<Text style={{ color: colors.text }}>Finns inte produkten med?</Text>
<View style={{ marginTop: 30 }}>
<TouchableOpacity
onPress={() => Linking.openURL('')}>
<Text
style={{
color: colors.text,
borderWidth: 1,
borderColor: colors.text,
padding: 10,
borderRadius: 5,
backgroundColor: colors.card,
}}>
KONTAKTA OSS
</Text>
</TouchableOpacity>
</View>
</View>
);
};
const renderItem = ({ item }) => {
return (
<View>
<TouchableOpacity
style={{
marginLeft: 20,
marginRight: 20,
elevation: 3,
backgroundColor: colors.card,
borderRadius: 10,
}}
onPress={() => {
setModalVisible(true);
setDetails(item);
}}>
<View style={{ margin: 10 }}>
<Text style={{ color: colors.text }}>{item.company}</Text>
<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>
);
};
return (
<View style={{ flex: 1, backgroundColor: colors.background }}>
<Modal
animationType="none"
hardwareAccelerated={true}
transparent={true}
visible={modalVisible}
onRequestClose={() => {
setModalVisible(!modalVisible);
}}>
<View
style={{
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: 'rgba(0,0,0,0.8)',
}}>
<View
style={{
backgroundColor: colors.Modal,
padding: 35,
borderRadius: 10,
width: '80%',
height: '80%',
}}>
<ScrollView showsVerticalScrollIndicator={false}>
<View style={{ marginTop: 20 }}>
<Text style={{ color: colors.text }}>{details.company}</Text>
<Text
style={{ color: colors.text, marginTop: 20, fontSize: 20 }}>
{details.name}
</Text>
<Text style={{ color: colors.text, marginTop: 20 }}>
{details.gluten}
</Text>
<Text style={{ color: colors.text, marginTop: 20 }}>
Ingredienser
</Text>
<Text style={{ color: colors.text, marginTop: 2 }}>
{details.ingredients}
</Text>
<Text style={{ color: colors.text, marginTop: 30 }}>
{details.id}
</Text>
</View>
</ScrollView>
<View
style={{
borderTopWidth: 1,
borderTopColor: colors.text,
marginBottom: 10,
}}></View>
<View
style={{ flexDirection: 'row', justifyContent: 'space-evenly' }}>
<TouchableOpacity
onPress={() => {
const updated = [...masterDataSource];
updated.find(
(item) => item.id === details.id,
).selected = true;
setMasterDataSource(updated);
navigation.navigate('Inköpslista', {
items: updated.filter((item) => item.selected),
});
}}>
<Text>Lägg i Inköpslistan</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={() => {
setModalVisible(false);
}}>
<Text style={{ alignSelf: 'center', color: '#FF0000' }}>
Stäng
</Text>
</TouchableOpacity>
</View>
</View>
</View>
</Modal>
<View
style={{
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
padding: 20,
backgroundColor: colors.Textinput,
elevation: 12,
}}>
<TextInput
style={{
flex: 1,
backgroundColor: '#fff',
borderTopLeftRadius: 5,
borderBottomLeftRadius: 5,
}}
placeholder=" SÖK PRODUKT NAMN / STRECKKOD"
placeholderTextColor="#000"
onChangeText={(text) => setSearch(text)}
value={search}
autoCapitalize="words"
/>
<Octicons
style={{
marginLeft: 1,
padding: 13,
backgroundColor: '#fff',
height: 49,
borderTopRightRadius: 5,
borderBottomRightRadius: 5,
}}
name="checklist"
size={25}
color="#000"
onPress={() =>
navigation.navigate('Inköpslista', {
items: masterDataSource.filter((item) => item.selected),
})
}
/>
</View>
<View style={{ flex: 1, marginTop: 20 }}>
<FlatList
data={filteredDataSource}
ItemSeparatorComponent={itemSeparatorComponent}
keyExtractor={(_, index) => index.toString()}
renderItem={renderItem}
initialNumToRender={4}
maxToRenderPerBatch={5}
windowSize={10}
removeClippedSubviews={true}
updateCellsBatchingPeriod={100}
showsVerticalScrollIndicator={true}
ListEmptyComponent={emptyComponent}
contentContainerStyle={{ paddingBottom: 20 }}
/>
</View>
</View>
);
}
SECOND SCREEN
import React from 'react';
import { View, Text, FlatList, Button } from 'react-native';
export default function ShoppingList({ route, navigation }) {
const RenderItem = ({ item }) => {
return (
<TouchableOpacity
style={{ marginHorizontal: 10, marginVertical: 15 }}
onPress={() => {}}>
<Text>{item.id}</Text>
<Text>{item.name}</Text>
</TouchableOpacity>
);
};
return (
<View
style={{
flex: 1,
alignItems: 'center',
justifyContent: 'center',
marginTop: 30,
}}>
<Button title="Go back" onPress={() => navigation.goBack()} />
<FlatList
data={route.params && route.params.items}
renderItem={RenderItem}
/>
</View>
);
}
Based on your question, this is the flow that you want
User has flat list with a set of items
When an item is clicked a modal is opened
If the user wants he clicks 'Add to cart' which will add item to cart and open cart.
When cart is opened user is shown a flatlist with the selected items.
Screen 1 : Home
Here you already have a modal but you pass a single item instead of an array.
So the better way is to use the masterDataSource state that you have and add a 'selected' property to it.
So the button in the Modal would be like this
<Button
title="Add and View Cart"
onPress={() => {
const updated = [...masterDataSource];
updated.find((item) => item.id === details.id).selected = true;
setMasterDataSource(updated);
navigation.navigate('Cart', {
items: updated.filter((item) => item.selected),
});
}}
/>
Once you click the Button you would be taken to the cart page with the items array which you have selected (This will have the previous items as well).
The Cart screen will have a Flatlist to show the items that are passed via params like below. RenderItem can be the code for your item.
<FlatList
data={route.params && route.params.items}
renderItem={RenderItem}
/>
You can run the sample below
https://snack.expo.io/#guruparan/cartexample
(Modal doesnt work properly on web you can try the android version)
According to React Native Docs, the prop data on FlatList should contain an Array, like this [{...}] or this [{...},{...},{...}...]. But you are trying to pass an Object to the FlatList on the ShoppingList screen, like this {...}.
On ShoppingList Screen when you're destructuring like the following
const { details } = route.params;
You are creating an object, which looks like this {...}
So you need to convert it to an array. Use the following code snippet
const itemInfo = []
itemInfo.push(details)
Now just pass itemInfo to data prop of FlatList.
Your ShoppingList screen should look like this.
import React from 'react';
import {
View,
FlatList,
Text,
} from 'react-native';
export default function ShoppingList({ route }) {
const { details } = route.params;
const itemInfo = [];
itemInfo.push(details);
return (
<View style={{ flex: 1, backgroundColor: "white" }}>
<FlatList
data={itemInfo}
keyExtractor={(item) => item.id.toString()}
renderItem={({ item }) => (
<View>
<Text style={{ color: "black" }}>{item.company}</Text>
<Text style={{ color: "black" }}>{item.name}</Text>
<Text style={{ color: "black" }}>{item.gluten}</Text>
<Text style={{ color: "black" }}>{item.id}</Text>
</View>
)}
/>
</View>
);
}
Hey guys I'm having an issue with navigation:
I select an item from the menuoption
I then call the 'testFunction'
Function will call an alert function so it is working
When I add the navigation part I get the error below:
undefined is not an object (evaluating '_this2.props.navigation.navigate')
Here is the import code:
import { NavigationScreenProp } from "react-navigation";
Here is where it is added to props:
interface NotificationDropdownProps {
navigation: NavigationScreenProp<any,any>
}
Here is where code is rendered:
class NotificationDropdown extends React.Component<Props, NotificationDropdownState> {
testFunction = () => {
this.props.navigation.navigate('Leagues')
};
<MenuOption
onSelect={() =>
{
if(notification.type == INotificationType.SYSTEM){
this.testFunction()
}
}
}
customStyles={{ optionWrapper: { padding: 0, margin: 0, zIndex: 100000000 } }}>
<View style={[styles.notificationContainer]} >
<View style={styles.iconArea}>
<View style={[styles.iconCircle]}>
<Icon name={this.getIconType(notification.type)}
color={this.notificationColor(notification.type)} size={26} />
</View>
</View>
<View style={styles.notificationData} >
<Text style={styles.notificationTxt}>{notification.text}</Text>
<Text style={styles.notificationDate}>{this.getDate(new Date(notification.dateCreated))}</Text>
</View>
</View>
</MenuOption>
Render:
render() {
return (
<Menu
renderer={Popover} rendererProps={{ placement: 'bottom', preferredPlacement: 'bottom' }}
opened={this.state.opened}
onBackdropPress={() => this.togglePopup()}
onClose={() => {
this.setState({ showEmpty: true });
// Store.dispatch(SetNotificationSeen());
}}
onOpen={() => {
Store.dispatch(SetNumberSeen(this.props.notifications.length));
}}
>
<MenuTrigger onPress={() => this.togglePopup()}>
<View style={{ padding: 10 }}>
<Icon name='ios-notifications-outline' color={'rgba(0,0,0,0.6)'} size={25} /></View>
</MenuTrigger>
<MenuOptions customStyles={{
optionsContainer: {
width: Dimensions.get('window').width * 0.75,
zIndex: 100000000,
elevation: 8,
borderRadius: 20
}
}}>
<View style={{ padding: 10 }}>
<Text style={{
fontSize: 20,
marginLeft: 10,
color: 'rgba(0,0,0,0.6)',
fontWeight: 'bold',
paddingBottom: 5
}}>Notifications</Text>
{this.props.notifications.length > 0 ? <FlatList
contentContainerStyle={{ borderRadius: 10 }}
// only allow 5 notifications
data={this.props.notifications.slice(0,5)}
renderItem={({ item }) => this.renderNotification(item)}
style={{ maxHeight: 200, zIndex: 5 }}
keyExtractor={this.keyExtractor}
/> : <Text style={styles.noNotifications}>No Notifications!</Text>}
</View>
</MenuOptions>
</Menu>
);
}
What am I missing? any help is welcome
Here is where the is called from the header.tsx
<View style={styles.icon}>
<NotificationDropdown />
{this.props.numberSeen < this.props.notificationCount ? <Badge value={this.props.notificationCount - this.props.numberSeen > 99 ? '99+' : this.props.notificationCount - this.props.numberSeen}
status="error" containerStyle={styles.badge} /> : null}
</View>
Ok so it seems that NavigationDropDown doesn't have the navigation props.
What you need is to pass the navigation props explicitly as it is not a screen component.
in the headercomponent.tsx
<View style={styles.icon}>
<NotificationDropdown navigation={this.props.navigation} />
{this.props.numberSeen < this.props.notificationCount ? <Badge value={this.props.notificationCount - this.props.numberSeen > 99 ? '99+' : this.props.notificationCount - this.props.numberSeen}
status="error" containerStyle={styles.badge} /> : null}
</View>
I assume that you have the navigation props in the headercomponent.tsx
I have a problem like picture below:
Text
As you guy can see I have info on every item: name and stock. Now I want to update stock on single item by type a number to text Input But when I type 3 into 1 Text Input, it fills 3 in all the remaining Text Input. This is my render Item:
renderItem = ({item}) => {
return (
<View style={styles.card}>
<TouchableOpacity
onPress={() => {
setCreateAt(item.WarehouseProduct.createdAt);
setNote(item.note);
setShowModal(true);
}}>
<Image
style={styles.tinyLogo}
source={require('../assets/images/fish.jpg')}
/>
</TouchableOpacity>
<View
style={{
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
marginLeft: 5,
height: 75,
width: 160,
}}>
<Text numberOfLines={2} style={styles.text}>
{item.name}
</Text>
<Text style={styles.text}>
{item.WarehouseProduct.stock.toString()}
</Text>
</View>
<View style={styles.iconcontainer}>
<Button title="clear" onPress={() => console.log(text)} />
</View>
<View
style={{
alignSelf: 'center',
marginLeft: 20,
borderWidth: 1,
borderRadius: 10,
}}>
<TextInput
style={{height: 40, width: 50}}
keyboardType="numeric"
onChangeText={(income) => setText(income)}
value={text}
/>
</View>
</View>
);
};
Can anyone help me solve this problem? Just give me an idea. Thanks all!
anything you put in renderitem will be rendered as much as your data in flatlist
<Flatlist
data={containtmultipledata}
renderItem={
....
<TextInput
style={{height: 40, width: 50}}
keyboardType="numeric"
onChangeText={(income) => setText(income)}
value={text}
/>
....
}
>
but you asign it to single value
you can change data you put in flatlist directly by index in item
<TextInput
style={{height: 40, width: 50}}
keyboardType="numeric"
onChangeText={(txt) => containMultipledata[index].yourObjectName = txt}
value={item.yourObjectName}
/>
Try this way
const [data, setData] = useState([... flat list data here default]);
const onTextChanged = (index, value) => {
const data = [...data];
data[index].availableStock = value; <-- "availableStock" is example key for showing way out of this -->
setData(data);
}
renderItem = ({item, index}) => {
return (
<View style={styles.card}>
......
<TextInput
...
onChangeText={(income) => onTextChanged(index, income)}
value={item.availableStock || 0}
/>
</View>
);
};