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

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));

Related

REACT NATIVE How can I highlight an item with a scrollview and increment/decrement the highlighted item?

I am building an 'Initiative Tracker' for home use. My goal is to have the first item at the top of the list highlighted by default and use a counter that keeps track of the turns to highlight the item to correspong with its turn.
Eg. When the '+' button is pressed, the next item should be highlighted and the previous item should return to normal.
I am currently using the map function to display an array. I feel like there should be a way to use the index and a style to achieve what I want, but I've had no luck so far.
Thanks in advance for any help or suggestions!
related code below:
let Encounter1Array = [
{ name: "goblin1", init: 5 },
{ name: "goblin2", init: 8 },
{ name: "goblin3", init: 15 },
{ name: "goblin4", init: 3 },
{ name: "goblin5", init: 9 },
];
function InitiativeTrackerScreen() {
const [encounter, setEncounter] = useState(Encounter1Array);
encounter.sort(function (x, y) {
return y.init - x.init;
});
return (
<KeyboardAvoidingView style={styles.wrapper}>
<ScrollView>
{encounter.map((item, index) => {
return (
<View key={index}>
<TouchableOpacity style={styles.ItemDisplayContainer}>
<View>
<View>
<Text style={{ fontStyle: "italic", fontSize: 16 }}>
{item.name}
</Text>
</View>
<View>
<Text style={{ fontSize: 12 }}>
Initiative: {item.init}
</Text>
</View>
</View>
</TouchableOpacity>
</View>
);
})}
</ScrollView>
</KeyboardAvoidingView>
);
}
You need extra state to keep track of the index of the element you want to highlight. Then you can use a conditional statement to match to right index and switch its style.
const P = ({ list }) => {
const [current, setCurrent] = useState(0);
return list.map((item, i) =>
<View style={i === current ? highlightStyle : style}>
<Button onPress={() => setCurrent(current + 1)}>
{"+"}
</Button>
{item}
</View>
);
};

I am using react-native-swiper-flatlist , but I cannot figure it out how to use scrollToIndex on button press

I am using react-native-swiper-flatlist , I want to scroll forward to some index by tapping button but no clue how to do it. Although I am very beginner to react native development.
I have searched alot but nothing helps, I get an error of undefined is not an object this2.swiper.scrollToIndex'
render() {
return (
<View style={styles.container}>
<SwiperFlatList
ref={swiper => {
this.swiper = swiper;
}}
data={[
{ key: "a" },
{ key: "b" },
{ key: "c" },
{ key: "d" },
{ key: "e" }
]}
index={0}
renderItem={({ item, index }) => (
<View>
<Image
style={styles.child}
source={require("../../assets/advertisementtwo.png")}
/>
<Image
style={styles.child}
source={require("../../assets/advertisementtwo.png")}
/>
<Image
style={styles.child}
source={require("../../assets/advertisementtwo.png")}
/>
<Image
style={styles.child}
source={require("../../assets/advertisementtwo.png")}
/>
<Button
title={"Next"}
onPress={this.swiper.scrollToIndex(1, true)}
style={{ backgroundColor: "white" }}
/>
</View>
)}
/>
</View>
);
}
Should swipe on button click
Here is the screenshot of the error I am getting
Try adding ref='swiper' as a SwiperFlatList prop,
Example
<SwiperFlatList ref='swiper'/>
this.refs.swiper._scrollToIndex(2)
For those who are using React hook instead of class, you can do sth like that to utilise the scrollToIndex function
//First, make a ref for storing the swiper instance inside your swiper compoent
const swiperRef = useRef<any>({});
//Second, store the reference
<SwiperFlatList
ref={(component) => { swiperRef.current._swiper = component; }}
>
//Later on, you can call the function like this
swiperRef.current._swiper.scrollToIndex({index: 2})

react-native "In this environment the sources for assign must be an Object" error with RNSwipeout

I have look at a couple of places and have tried a few workarounds but none of them worked either.
With the following Code (A Flatlist with Swipeout to delete Listelements):
<FlatList data = {this.state.needList}
refreshing = {this.refreshing}
onRefresh = {this.refreshItems.bind(this)}
renderItem = {({item, index}) => {
let swipeoutBtns = [
{
text: 'Delete',
backgroundColor: 'red',
onPress: () => {
console.log(this.itemsRef.child(this.state.needList[index].key));
this.itemsRef.child(this.state.needList[index].key).remove();
this.getItems(this.itemsRef);
}
},
];
return(
<Swipeout right = {swipeoutBtns}
autoClose = {true}>
<View style = {[styles.flatListCss,
{backgroundColor: index %2 == 0 ? '#dbdbdb' : 'white'}]}>
<Text style = {styles.flatListCssText}>{item.item}</Text>
<Text style = {styles.flatListCssText}>{item.amount}
<Text style = {styles.flatListCssText}> {item.value}</Text>
</Text>
</View>
</Swipeout>
);
}}>
</FlatList>
I get the following Error message:
"TypeError: In this environment the sources for assign MUST be an object."
I have followed the example from here: https://github.com/dancormier/react-native-swipeout
For some reason it doesn´t work for me.
A fix would be perfect. A workaround would be great as well.
Thanks ahead!

react-native-elements checkbox update value

I have the following code and for some reason the checkbox is not updated when I click on them. Does anyone know what might be the problem? I am using CheckBox from react-native-elements. The checked property is based on whether a value exists in a set. The onpress function updates the state variable and I am able to get the correct values from the state variable. Thanks!
constructor(props) {
super(props);
this.state = {
interests: new Set(),
brands: new Set(),
medicalCondition: new Set(),
errorMessage: '',
loading: false
}
}
onPressHandler = (event, value, keyName) => {
let tempCheckedValues = new Set(this.state[keyName]);
tempCheckedValues.has(value) ? tempCheckedValues.delete(value) : tempCheckedValues.add(value);
console.log(tempCheckedValues);
this.setState({[keyName] : tempCheckedValues});
}
renderCheckboxGroup = (checkboxList, keyName) => {
return checkboxList.map((value, index) => {
return (
<CheckBox
key={index}
title={value}
onPress={(event) => this.onPressHandler(event, value, keyName)}
checked={this.state[keyName].has(value.toLowerCase())}
/>
)
})
}
render() {
const interestsConst = ["Tennis", "Golf", "Shopping", "Movie", "Hiking", "Reading", "Diving", "Investing"];
const brandsConst = ["Chanel", "Louis Vuitton", "H&M", "ZARA", "Hermes", "Gucci", "Cartier", "Burberry", "Nike", "Adidas", "Lululemon", "Athleta"];
const medicalConditionConst = ["Hypertension", "Hyperlipidemia", "Diabetes", "Back pain", "Anxiety", "Asthma", "Cancer", "Depression", "Shingles"];
return (
<View style={styles.container}>
<ScrollView>
<View style={styles.cardGroup}>
<Card title='Interests'>
{this.renderCheckboxGroup(interestsConst, 'interests')}
</Card>
</View>
<View style={styles.cardGroup}>
<Card title='Brands'>
{this.renderCheckboxGroup(brandsConst, 'brands')}
</Card>
</View>
<View style={styles.cardGroup}>
<Card title='Medical Conditions'>
{this.renderCheckboxGroup(medicalConditionConst, 'medicalCondition')}
</Card>
</View>
</ScrollView>
</View>
)
}
}

How to get value on button click in array 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.