How to get value on button click in array react native - react-native

Hello please help me to sort out from this error.
btnDynamic()
{
return myArr.map(function(data,index){
return(
<TouchableHighlight key={index} onPress={()=> this.btnCLick()} style={styles.btn} underlayColor='transparent'>
<View style={{alignItems:'center',justifyContent:'center'}}>
<Text ref={index} style={{fontSize:6,fontWeight:'bold'}}>{data.category}</Text>
</View>
</TouchableHighlight>
)
});
}
above is my function which gives multiple buttons depend on my another function gives response.
but main problem is button click method gives an error like this.
"this.btnCLick is not a function.(in _this3.btnCLick()),this3.btnClick" is undefine.
this is my btn Click function
btnCLick(text){
Alert.alert("Button Is Clicked",text);
}
please guys help me to solve this error.
Thanks in advance.

I would like to share how to get value on button click array react native
const OpenGallery = () => {
return this.state.photos.map((p, i) => {
let selectImage = p.node.image.uri;
return (
<TouchableOpacity
key={i}
onPress={this.selectImage.bind(this, selectImage)}
>
<Thumbnail
square
style={{
width: 120,
height: 120,
margin: 3
}}
source={{ uri: p.node.image.uri }}
/>
</TouchableOpacity>
);
});
};
Create funtion
selectImage = image => {
const { navigation } = this.props;
this.setState({
isGallery: !this.state.isGallery
});
this.selectedImage = image;
};
According to this concept I can access current array value through button click event.
I hope it will help you.

Related

How to use hooks as image's source in react native?

Im making this menu that when the user clicks at an option, it changes the background image, but i cant use the hook that i created as a parameter to the source of the image. Can someone find where im wrong and how to fix it?
Heres the part of my code referents to the menu and the hooks:
export function Home(){
let imagens = {
vovo: '../assets/vovoJuju.png',
mc: '../assets/mcJuju.png',
pato: '../assets/patoJuju.png',
}
const navigation = useNavigation<any>();
const [showBottomSheet, setShowBottomSheet] = React.useState(false);
const [param, setParam] = useState(1);
const [skin, setSkin] = useState('vovo')
const hide = () => {
setShowBottomSheet(false)
}
function handleAbout(){
navigation.navigate('About');
}
useEffect(() => {
if(param==1){
setSkin('vovo');
}
else if(param==2){
setSkin('mc');
}
else if(param==3){
setSkin('pato');
}
})
return(
<SafeAreaView style={styles.container}>
<TouchableOpacity onPress={handleAbout}>
<Counter />
</TouchableOpacity>
<TouchableOpacity onPress={() => {
setShowBottomSheet(true)
}}
>
<Image source={skin} style={styles.imgvj}/>
</TouchableOpacity>
<BottomSheet show={showBottomSheet} height={290} onOuterClick={hide}>
<Pressable onPress={hide} style={styles.bottomSheetContent}>
<Image source={barrinhaLoja} style={styles.barra}/>
</Pressable>
<View style={styles.conteudoLoja}>
<View style={styles.marginLeft48}>
<TouchableOpacity onPress={() => {
setParam(1);
}}>
<Image source={vovoJuju} style={styles.vovo}/>
<Text style={styles.legendasLoja}>Vovó Juju</Text>
</TouchableOpacity>
</View>
<View>
<TouchableOpacity onPress={() => {
setParam(2);
}}>
<Image source={mcJuju} style={styles.mc}/>
<Text style={styles.legendasLoja}>MC Juju</Text>
</TouchableOpacity>
</View>
<View>
<TouchableOpacity onPress={() => {
setParam(3);
}}>
<Image source={patoJuju} style={styles.pato}/>
<Text style={styles.legendasLoja}>Pato Juju</Text>
</TouchableOpacity>
</View>
</View>
</BottomSheet>
I created the "let imagens", "const param", "const skin" and the "useEffect trying" to make this function. I already tried using the source in different ways such as source={skin} and source={imagens[skin]} but it havent worked.
I'm not certain if this solves your problem, but here's how the first few lines of your component should look like without useEffect:
const imagens = {
vovo: '../assets/vovoJuju.png',
mc: '../assets/mcJuju.png',
pato: '../assets/patoJuju.png',
};
export function Home(){
const navigation = useNavigation<any>();
const [showBottomSheet, setShowBottomSheet] = React.useState(false);
const [param, setParam] = useState(1);
const hide = () => {
setShowBottomSheet(false)
}
function handleAbout(){
navigation.navigate('About');
}
let skin = 'vovo';
switch(param) {
case 1: skin = 'vovo'; break;
case 2: skin = 'mc'; break;
case 3: skin = 'pato'; break;
}
return /* the rest goes here */
}
To reference the actual image, you would use something like {imagens[skin]}.
I moved imagens outside of this function because it never changes, but it doesn't impact anything otherwise.

Call a function once onPress then display other function

I'm doing a react-native school project and i'm willing to know how to call a function on first press then display another function on other clicks :
<TouchableOpacity style={styles.btnMiddle} onPress={() => buyFishes(1)}>
<View style={styles.fish}>
<Text style={styles.shptxt}>50</Text>
<Image style={styles.coin2}source={require("../../assets/img/coin.png")} />
</View>
</TouchableOpacity>
here is my button, in my project this button is displayed on the Shop Screen and I need it to cost 50 on the first press (to unlock it), then I want it to stop costing 50 and just call another function.
here is my function to buy an item
const buyFishes = (id) => {
fishes.map(fishes => {
if(fishes.id === id)
{
if(Gold >= fishes.cost)
{
setGold(Gold - fishes.cost);
}
}
if (Gold < fishes.cost)
{
onPress: () => Alert.alert("Not enough Gold Kiddo !");
}
}
);
};
Any Idea ?
Thanks
Just add a state to your component and use it to call the functions you want accordingly.
const [clicked,setClicked] = useState(false);
<TouchableOpacity style={styles.btnMiddle} onPress={onPressHandler}>
<View style={styles.fish}>
<Text style={styles.shptxt}>50</Text>
<Image style={styles.coin2}source={require("../../assets/img/coin.png")} />
</View>
</TouchableOpacity>
const onPressHandler = (id) => {
setClicked(true);
if(clicked)
{
// call second function
}
else
{
// call first function
}
};

how do i get a value picked from another screen?

im using navigation to pass between screens.
now,im trying to figure out how can i get a value from second screen to the first screen ?
the user needs to pick a color value from the second screen and return selcted color to the first screen.
this is the code im using .
enter code here
<CustomButton
style={styles.buttonPicker}
darkMode={this.props.darkMode}
title={'pick a color'}
onPress={() => {
this.props.navigation.navigate('ColorPickerScreen', {
onSubmit: (namecolor) => {
console.log('55555555555555', { getNameColor })
},
})
}}
></CustomButton>
enter code here
onSelect = (color) => this.props.navigation.navigate('CreatenewtTipul')
render() {
return (
<Image
style={styles.img}
source={require('../components/icons/color-wheel.png')}
/>
<ColorPicker
colors={this.state.colors}
selectedColor={this.state.selectedColor}
onSelect={this.onSelect}
/>
<Text>Selected Color = {this.state.selectedColor}</Text>
</View>
)
}
}
tnx for any help
arik :)
To pass value from screen A to screen B:
navigation.navigate('ScreenB', {
itemId: 86,
otherParam: 'anything you want here',
});
To access that value in Screen A:
const { itemId, otherParam } = route.params;
Where were route here is part of the screen's props, check the guide here for more info
im not trying to pass a value to the second screen.
im trying to get a value from the second screen to the first screen.
You can pass a function as a callback from the first screen to the second screen in params on call that on your second screen.
function Screen1(props) {
const onSelect = (selectedColor) => {
console.log('selectedColor', selectedColor)
}
const navigateToSecondScreen = () => {
props.navigation.navigate('Screen2', {
onColorSelect: onSelect
})
}
return(
<View>
<TouchableOpacity onPress={navigateToSecondScreen}>
<Text>Go to second screen</Text>
</TouchableOpacity>
</View>
)
}
//Second Screen
function Screen2(props) {
const {onColorSelect} = props.route.params;
return(
<View>
<TouchableOpacity onPress={() => {onColorSelect('color value')}}>
<Text>your other code here</Text>
</TouchableOpacity>
</View>
)
}
The idea is just to call the function which you have passed as a param from Screen1

Calling modal on a list of products opens the modal for all of them instead of just the one being clciked

I am making a react native app that loads data from google firebase and then display it on a page, when a user clicks on any of the products aa modal will open to show more datails.
I am using useEffect to load the data on page load then display then results:
const fetchData = async () => {
const categories = db.collection("productsDB");
const collections = await categories
.limit(6)
.onSnapshot((querySnapshot) => {
const items = [];
querySnapshot.forEach((documentSnapshot) => {
items.push({
...documentSnapshot.data(),
key: documentSnapshot.id,
});
});
setItems(items);
setLoading(false);
});
return () => collections();
};
useEffect(() => {
fetchData();
}, []);
and the show them like this:
{loading ? (
<ActivityIndicator />
) : (
items.map((item) => (
<TouchableOpacity
style={styles.queryResult}
key={item.key}
onPress={() => {
setModalVisible(!modalVisible);
}}
>
<View style={styles.queryResultContent}>
<Image
style={{ width: 100, height: 100 }}
source={{ uri: String(item.images) }}
/>
<View>
<Text style={styles.queryInfoHeader}>{item.name}</Text>
</View>
</View>
<View>
<ProductModal
isModalVisible={modalVisible}
setModalVisible={setModalVisible}
navigation={navigation}
{...item}
/>
</View>
</TouchableOpacity>
))
)}
when I open the modal, it opens the modal for all of the products and doesnt really matter if I click on the first product or what, it opens all of the modals, and I am not sure how to get rid of this!
is there any better way to write this function?
You're using the same modalVisible flag for all of your modals; therefore, they either are all visible or all hidden.
Why not have a single modal rather than rendering a bunch of them in the loop, and pass the item as a prop to it?

undefined is not an object (evaluating '_this2.onRadioPressed')

I'm building radio buttons using my component and the buttons are built fine but the onPress is not working. I get the error in the title on click of the radio button. I suspect, based on the error, that 'this' is not what I think it is. Any help is appreciated. Here's the relevant code:
let radio_props = [
{label: 'forward', value: 0 },
{label: 'back', value: 1 }
];
<RadioBtn
radioGroupLabel={'Main Label'}
radioLabels={radio_props}
style={styles.radioElement}>
</RadioBtn>
Then in my RadioBtn.js file...
onRadioPressed = (val) => {
console.log('VAL:', val);
this.setState({selectedValue:val});
};
renderRadios(obj, i) {
console.log('OBJ:', obj);
return (
<View style={styles.firstRadioContainer}>
<TouchableOpacity
onPress={(value, index) => {
this.onRadioPressed(obj.value)
}}
underlayColor='#f1c40f'>
<Text value={obj.value} style={styles.radio}>{obj.label}</Text>
</TouchableOpacity>
</View>
)
};
render() {
let renderedRadios = this.props.radioLabels.map(this.renderRadios);
return (
<View>
<View style={styles.radioLabelContainer}>
<Text style={styles.radioLabel}>{this.props.radioGroupLabel}</Text>
</View>
<View style={styles.radioGrp}>
{renderedRadios}
</View>
</View>
);
};
You are right, this in renderRadios method is no longer pointing to RadioBtn class because of the way you invoke in the array's map method.
Try changing to the following by using arrow function expression:
let renderedRadios = this.props.radioLabels.map((o, i) => this.renderRadios(o, i));