I am trying to randomize the value from my drop down picker and at the same time, to pass on to the next screen but I am having trouble on randomizing the value.
Drop Down Picker
const [open, setOpen] = useState(false);
const [value, setValue] = useState(null);
const [items, setItems] = useState([
{label: 'Fast Food', value: 'Fast Food'},
{label: 'Western', value: 'Western'},
{label:'Beverage', value:'Berverage'},
{label:'Chinese', value:'Chinese'},
{label: 'Korean', value: 'Korean'},
{label: 'Taiwanese', value: 'Taiwanese'},
{label: 'Malay', value: 'Malay'},
{label: 'Indonesian', value: 'Indonesian'},
{label: 'Indian', value: 'Indian'},
{label: 'Vietnamese', value: 'Vietnamese'},
{label: 'Japanese', value: 'Japanese'},
{label: 'Italian', value: 'Italian'},
{label: 'Desserts', value: 'Desserts'},
{label: 'Others', value: 'Others'},
]);
Function
const setRandomValue = () => {
const randomIndex = Math.floor(Math.random() * items.length);
setValue([items[randomIndex].label.toLowerCase()]);
console.log(randomIndex)
}
Button
<TouchableOpacity
onPress={setRandomValue}
style = {styles.button}
>
<Text style = {styles.buttonText}>Random</Text>
</TouchableOpacity>
The error I get is "Cannot find Variable:setRandomValue'' Is there something I need to download?
HomeScreen code (Without the styling)
import { TouchableOpacity, StyleSheet, Text, View } from 'react-native'
import React from 'react'
import { auth } from '../firebase'
import { useNavigation } from '#react-navigation/core'
import { signOut } from 'firebase/auth'
import DropDownPicker from 'react-native-dropdown-picker'
import { useEffect, useState } from 'react'
const HomeScreen = () => {
const navigation = useNavigation()
const [open, setOpen] = useState(false);
const [value, setValue] = useState(null);
const [items, setItems] = useState([
{label: 'Fast Food', value: 'Fast Food'},
{label: 'Western', value: 'Western'},
{label:'Beverage', value:'Berverage'},
{label:'Chinese', value:'Chinese'},
{label: 'Korean', value: 'Korean'},
{label: 'Taiwanese', value: 'Taiwanese'},
{label: 'Malay', value: 'Malay'},
{label: 'Indonesian', value: 'Indonesian'},
{label: 'Indian', value: 'Indian'},
{label: 'Vietnamese', value: 'Vietnamese'},
{label: 'Japanese', value: 'Japanese'},
{label: 'Italian', value: 'Italian'},
{label: 'Desserts', value: 'Desserts'},
{label: 'Others', value: 'Others'},
]);
const handleSignOut = async () =>{
try{
await signOut(auth)
console.log("Signed out successfully")
navigation.replace("Login")
}catch (error) {
console.log({error});
}
const setRandomValue = () => {
const randomIndex = Math.floor(Math.random() * items.length);
setValue([items[randomIndex].label.toLowerCase()]);
console.log(randomIndex)
}
}
return (
<View style = {styles.container}>
<Text>Welcome {auth.currentUser?.email}</Text>
<Text></Text>
<Text>What cusine would you like to eat today?</Text>
<DropDownPicker
open={open}
value={value}
items={items}
setOpen={setOpen}
setValue={setValue}
setItems={setItems}
/>
<TouchableOpacity
onPress={() => navigation.navigate("SubScreen1", {paramKey:value})}
style = {styles.button}
>
<Text style = {styles.buttonText}>Search</Text>
</TouchableOpacity>
<TouchableOpacity
// onPress={setRandomValue}
style = {styles.button}
>
<Text style = {styles.buttonText}>Random</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={handleSignOut}
style = {styles.button}
>
<Text style = {styles.buttonText}>Sign Out</Text>
</TouchableOpacity>
</View>
)
}
export default HomeScreen
It has been pointed out to me that I am console logging the index in this case as my console log is for the randomIndex. So I wanted to see if I can get the value that I have defined by throwing it to a variable and console logging that. But the result I get was undefined. How do I solve this?
Edited Function
const setRandomValue = () => {
const randomIndex = Math.floor(Math.random() * items.length);
const randomValue = setValue([items[randomIndex].label.toLowerCase()]);
console.log(randomIndex)
console.log(randomValue)
}
Related
How can I maintain the scroll position when I switch from vertical to horizontal orientation in the flat list? A change of the horizontal prop resets the scroll position.
<FlatList
data={DATA}
renderItem={renderItem}
keyExtractor={(item) => item.id}
horizontal={isHorizontal} // change triggers reset to first item
/>
Flatlist has a method called scrollToIndex that is able to scroll to the specific item. You can leverage this to return to the correct scroll position by saving the index of the item that is in view in a useState and then passing the state to the scrollToIndex function whenever ishorizontal state is changed. I've created a basic example below.
import React, { useEffect, useState, useRef } from 'react';
import { SafeAreaView, View, FlatList, StyleSheet, Text, StatusBar, Dimensions } from 'react-native';
const DATA = [
{
id: 'bd7acbea-c1b1-46c2-aed5-3ad53abb28ba',
title: 'First Item',
},
{
id: '3ac68afc-c605-48d3-a4f8-fbd91aa97f63',
title: 'Second Item',
},
{
id: '58694a0f-3da1-471f-bd96-145571e29d72',
title: 'Third Item',
},
{
id: '58694a0f-3da1-471f-bd96-145571e29d73',
title: 'forth Item',
},
{
id: '58694a0f-3da1-471f-bd96-145571e29d74',
title: 'fifth Item',
},
{
id: '58694a0f-3da1-471f-bd96-145571e29d71',
title: 'sixth Item',
},
{
id: '58694a0f-3da1-471f-bd96-145571e29dfs',
title: 'seven Item',
},
{
id: '58694a0f-3da1-471f-bd96-145571e29ddd',
title: 'eight Item',
},
];
const Item = ({ title }) => (
<View style={styles.item}>
<Text style={styles.title}>{title}</Text>
</View>
);
const App = () => {
const [isHorizontal, setIsHorizontal] = useState(false)
const [index, setIndex] = useState(0)
const flatListRef = useRef(null)
const renderItem = ({ item }) => (
<Item title={item.title} />
);
useEffect(() => {
const subscription = Dimensions.addEventListener(
"change",
({ window: { width, height } }) => {
if (width < height) {
setIsHorizontal(true)
} else {
setIsHorizontal(false)
}
}
);
return () => subscription?.remove();
});
useEffect(() => {
if(flatListRef.current) {
console.log(index);
flatListRef.current?.scrollToIndex({index: index})
}
}, [isHorizontal]);
const onViewRef = React.useRef((viewableItems) => {
setIndex(viewableItems.viewableItems[1].index);
});
return (
<SafeAreaView style={styles.container}>
<FlatList
initialScrollIndex={index}
ref={flatListRef}
data={DATA}
renderItem={renderItem}
keyExtractor={item => item.id}
onViewableItemsChanged={onViewRef.current}
isHorizontal={isHorizontal}
/>
</SafeAreaView>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
marginTop: StatusBar.currentHeight || 0,
},
item: {
backgroundColor: '#f9c2ff',
padding: 20,
margin:100
},
title: {
fontSize: 32,
},
});
export default App;
Why I get this error Message?
Warning: Each child in a list should have a unique "key" prop.
import * as React from 'react';
import { StyleSheet, Text, View, TouchableOpacity, Image, Dimensions, Animated, FlatList } from 'react-native';
const StoryProfile = () => {
const dataStory = [
{
type: 'NORMAL',
item: {
id: '1',
image: 'https://picsum.photos/200',
}
},
{
type: 'NORMAL',
item: {
id: '2',
image: 'https://picsum.photos/200',
}
},
{
type: 'NORMAL',
item: {
id: '3',
image: 'https://picsum.photos/200',
}
},
{
type: 'NORMAL',
item: {
id: '4',
image: 'https://picsum.photos/200',
}
},
{
type: 'NORMAL',
item: {
id: '5',
image: 'https://picsum.photos/200',
}
},
{
type: 'NORMAL',
item: {
id: '6',
image: 'https://picsum.photos/200',
}
},
];
const Item = React.memo(({ image }) => {
return (
<View>
<Image source={{uri: image}} height={48} width={48} resizeMode="contain" />
</View>
)
});
const renderItem = ({ item }) => {
return (
<Item image={item.image} />
)
};
return (
<View style={styles.container}>
<FlatList
data={dataStory}
keyExtractor={item => item.id}
key={Math.random(1000)}
renderItem={renderItem}
/>
</View>
)
};
const styles = StyleSheet.create({
container: {
flex: 1
}
})
export default StoryProfile;
I have tried a key prop but thats not working. What I am doing wrong ?
........................................................................................................................................................................................................................
No need to have a key prop on a FlatList component:
<FlatList
data={dataStory}
keyExtractor={item => item.id}
key={Math.random(1000)} {/* No need to have a key attribute on FlatList */}
renderItem={renderItem}
/>
When you add a keyExtractor={item => item.id}, it will search the id on each object of your dataStory, which is undefined in your case, so the key in your case is the same undefined.
So, the first solution is:
Instead of having:
{
type: 'NORMAL',
item: {
id: '1',
image: 'https://picsum.photos/200',
}
}
You should have this:
{
id: '1',
type: 'NORMAL',
item: {
image: 'https://picsum.photos/200',
}
}
The second solution is to change the keyExtractor to be:
keyExtractor={item => item.item.id}
or:
keyExtractor={({item}) => item.id}
I am trying to implement react native calendar agenda with marked dates and items dynamically from Firebase. I am not sure how to create the array required for this display. Below code gets data from firebase but I need to display the same. Please help me in creating array required by react native calendar
import React, {useState, useContext, useEffect} from 'react';
import { View, TouchableOpacity, StyleSheet } from 'react-native';
import { CalendarList, Agenda } from "react-native-calendars";
import { Button, Card, Layout, Text } from '#ui-kitten/components';
import moment from 'moment';
import AppContext from './AppContext';
import firebase from '../firebase';
function Calendar() {
const todaysDate = new moment(new Date()).format("DD-MM-YYYY")
const [items, setItems] = useState([]);
const myContext = useContext(AppContext);
const groups = myContext.userGroups;
useEffect(() => {
function loadItems() {
firebase.database().ref("events").on("value", (userSnapshot) => {
userSnapshot.forEach(grpid => {
grpid.forEach(element => {
const gid = grpid.key;
groups.forEach(usergroupid => {
const usergrpid = usergroupid.groupid;
if(usergrpid === gid){
const id = element.key;
const sdate = moment((element.child('start').val()), 'DD-MM-YYYY');
console.log("sdate", sdate);
const start = moment(sdate).toDate();
console.log("start", start);
const edate = moment((element.child('end').val()), 'DD-MM-YYYY');
const end = moment(edate).toDate();
const title = element.child('title').val();
//items[sdate] = [];
items[sdate] = {name:title}
setItems(items);
console.log("new",items);
}
});
});
});
});
}
loadItems();
}, [])
const renderItem = (items) => {
return(
<TouchableOpacity>
<Card>
<View>
<Text>{items}</Text>
</View>
</Card>
</TouchableOpacity>
)
}
return (
<View style={{ paddingTop: 50, flex: 1 }}>
<Agenda
current={todaysDate}
minDate={todaysDate}
markedDates={{
'2020-12-24': [{selected: true, marked: true, selectedColor: 'blue', Name:"hello"}],
'2020-12-25': {marked: true},
'2020-12-26': {marked: true, dotColor: 'red', activeOpacity: 0},
}}
items={items}
renderItem={renderItem}
/>
</View>
);
}
export default Calendar;
You only need to add square braces around the dates
markedDates={{
[start]: {selected: true, marked: true, selectedColor: 'blue', Name:"hello"},
[edate]: {marked: true},
[end]: {marked: true, dotColor: 'red', activeOpacity: 0},
}}
I am new to react native, I need a bit help in integrating a library react-native-tab-view. Can I get a step by step guide how to integrate it with a new project?
First run the following command in terminal
expo install react-native-gesture-handler react-native-reanimated
Paste this in your App.js and you will be done
import * as React from 'react';
import { View, StyleSheet, Dimensions } from 'react-native';
import { TabView, SceneMap } from 'react-native-tab-view';
const FirstRoute = () => (
<View style={[styles.scene, { backgroundColor: '#ff4081' }]} />
);
const SecondRoute = () => (
<View style={[styles.scene, { backgroundColor: '#673ab7' }]} />
);
const initialLayout = { width: Dimensions.get('window').width };
export default function TabViewExample() {
const [index, setIndex] = React.useState(0);
const [routes] = React.useState([
{ key: 'first', title: 'First' },
{ key: 'second', title: 'Second' },
]);
const renderScene = SceneMap({
first: FirstRoute,
second: SecondRoute,
});
return (
<TabView
navigationState={{ index, routes }}
renderScene={renderScene}
onIndexChange={setIndex}
initialLayout={initialLayout}
/>
);
}
const styles = StyleSheet.create({
scene: {
flex: 1,
},
});
red error screen 1
Cannot read property 'configureProps' of undefined
I was using the react-tab-view with react Hooks and typescript but I have some issues somebody could give me a hand...
import React, { useState } from 'react';
import { View, Text, TouchableOpacity, StyleSheet, Dimensions } from 'reactnative';
import { TabView, SceneMap } from 'react-native-tab-view';
const FirstRoute = () => (
<View style={[styles.scene, { backgroundColor: '#ff4081' }]} />
);
const SecondRoute = () => (
<View style={[styles.scene, { backgroundColor: '#673ab7' }]} />
);
interface Props {
navigation: any;
}
export default function Home(props: Props) {
const [rar, setRar] = useState({
index: 0,
routes: [
{ key: 'first', title: 'First' },
{ key: 'second', title: 'Second' },
]
});
var NativeAppEventEmitter = require('RCTNativeAppEventEmitter');
return (
<View>
<TouchableOpacity onPress={props.navigation.openDrawer}>
<Text>hola desde home</Text>
</TouchableOpacity>
<TabView
navigationState={rar}
renderScene={SceneMap({
first: FirstRoute,
second: SecondRoute,
})}
onIndexChange={index => ({ index })}
initialLayout={{ width: Dimensions.get('window').width, height: 250 }}
/>
</View>
)
}
const styles = StyleSheet.create({
scene: {
flex: 0.3,
},
});
change
onIndexChange={index => ({ index })}
to
onIndexChange={index => setRar({ ...rar, index })}
that should fix the error you are facing
import React, { useState, useEffect } from 'react';
import { Container } from './styles';
import { View, StyleSheet, Dimensions } from 'react-native';
import { TabView, SceneMap } from 'react-native-tab-view';
const LatestRoute = () => (
<View style={[styles.scene, { backgroundColor: '#ff4081' }]} />
);
const FavoritesRoute = () => (
<View style={[styles.scene, { backgroundColor: '#673ab7' }]} />
);
const AllRoute = () => (
<View style={[styles.scene, { backgroundColor: '#673ab7' }]} />
);
const styles = StyleSheet.create({
scene: {
flex: 1,
},
});
export default function Main() {
const initialState = {
index: 0,
routes: [
{ key: 'latest', title: 'Latest' },
{ key: 'favorites', title: 'Favorites' },
{ key: 'all', title: 'All' },
],
};
const [ state, setState ] = useState(initialState);
function selectTab ( index ) {
this.initialState = {
index: index,
routes: [
{ key: 'latest', title: 'Latest' },
{ key: 'favorites', title: 'Favorites' },
{ key: 'all', title: 'All' },
],
};
return setState(this.initialState);
}
return (
<Container>
<TabView
navigationState={state}
renderScene={SceneMap({ latest: LatestRoute, favorites: FavoritesRoute, all: AllRoute })}
onIndexChange={ (index) => selectTab(index) }
initialLayout={{ width: Dimensions.get('window').width, height : Dimensions.get('window').height }}
/>
</Container>
);
}