How to select a single radio button at a time in react native flatlist - react-native

I am using react-native-radio-button to implement a flatlist with radio button as shown in the image.
[![enter image description here][1]][1]
But i am unable to select a single radio button at a time in flatlist.
Here is my code
import React from 'react';
import { StyleSheet, View, Text, FlatList, TouchableOpacity, Image, LayoutAnimation, UIManager, Platform } from 'react-native';
import RadioButton from 'react-native-radio-button';
import PHARMACY from './api/mockPharmacyList';
import { Colors, Fonts } from '../../styles';
interface IState {
selected: number;
selectedIndex: number;
data: any;
expanded: boolean;
checked: boolean;
}
export class TransferToPharmacy extends React.Component<{}, IState> {
constructor(props) {
super(props);
this.state = {
data: PHARMACY,
selected: 0,
selectedIndex: 0,
expanded: true,
checked: false,
};
this.onPress = this.onPress.bind(this);
this.renderItem = this.renderItem.bind(this);
this.renderSeparator = this.renderSeparator.bind(this);
this._keyExtractor = this._keyExtractor.bind(this);
this.changeLayout = this.changeLayout.bind(this);
this.onCheck = this.onCheck.bind(this);
if (Platform.OS === 'android') {
UIManager.setLayoutAnimationEnabledExperimental(true);
}
}
changeLayout = () => {
LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut);
this.setState({ expanded: false });
}
getInitialState() {
return {
value: 0,
};
}
onPress(value) {
this.setState({ selected: value });
}
_keyExtractor = (item, index) => item.id;
onCheck = () => {
const { checked } = this.state;
if (checked === true) {
this.setState({ checked: false });
} else {
this.setState({ checked: true });
}
}
renderItem(data) {
const { item } = data;
return (
<View style={styles.itemBlock}>
<TouchableOpacity >
<View style={styles.arrowIconStyle}>
<Text style={styles.pharmacyText}>{item.name}</Text>
<RadioButton
innerColor={Colors.darkBlue}
outerColor={Colors.lightGray}
animation={'bounceIn'}
isSelected={this.state.selectedIndex === 0}
onPress={this.onPress}
/>
</View>
</TouchableOpacity>
<Text>{item.key1}</Text>
<View style={{ height: this.state.expanded === true ? 90 : 0, overflow: 'hidden' }}>
<View style={{ flexDirection: 'row', marginTop: 5, padding: 10 }}>
<Image style={[styles.itemImage, { width: 15, height: 15, margin: 1 }]} source={require('./images/map_pic_icon.png')} />
<Text style={styles.itemText}>{item.location}</Text>
</View>
<View style={{ flexDirection: 'row', marginTop: 5, padding: 10 }}>
<Image style={[styles.itemImage, { width: 15, height: 15, margin: 1 }]} source={require('./images/phone_icon.png')} />
<Text style={styles.itemText}>{item.phone}</Text>
</View>
</View>
</View>
);
}
renderSeparator() {
return <View style={styles.separator} />;
}
render() {
return (
<View style={styles.container} >
<Text style={styles.textStyle}>Transfer to Pharmacy</Text>
<View style={styles.childViewStyle}>
<FlatList
keyExtractor={this._keyExtractor}
data={this.state.data}
renderItem={this.renderItem}
ItemSeparatorComponent={this.renderSeparator}
/>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
textStyle: {
fontSize: 18,
color: Colors.black,
marginTop: 30,
marginLeft: 20
},
childViewStyle: {
margin: 20,
},
itemBlock: {
paddingVertical: 15,
},
itemImage: {
width: 50,
height: 50,
borderRadius: 25,
margin: 10
},
itemText: {
fontSize: 16,
justifyContent: 'center',
color: Colors.darkySkyBlue
},
itemName: {
fontSize: 20,
color: Colors.black,
},
separator: {
borderRadius: 4,
borderWidth: 1,
borderColor: Colors.lightGray,
},
pharmacyText: {
fontSize: 16,
fontFamily: Fonts.bold,
color: Colors.black
},
radioStyle: {
marginTop: 10,
marginRight: 50,
justifyContent: 'space-between'
},
arrowIconStyle: {
flexDirection: 'row',
justifyContent: 'space-between',
padding: 10
// flex: 1
}
});
with this code i am not able to select the radio button
Please let me know where it is going wrong as i am unable to select radio button in the flatlist separately.
i have changed onPress() like this
onPress( index) {
this.setState({ selected: index, });
}
and in renderItem method i have changed it like this
const { item, index } = data;
<RadioButton
innerColor={Colors.darkBlue}
outerColor={Colors.lightGray}
animation={'bounceIn'}
isSelected={this.state.selected === index}
onPress={() => this.onPress(index)}
/>
Now the output is like this
Now the first radio button is selected but when i tried to select other radio buttons they are not getting selected.
Here is my mock data file which is used for Flatlist.
export const PHARMACY = [
{
key: 0,
name: 'Plaza Pharmacy',
type: 'Urgent Care Center - 4.01 mi',
location: '3417 Gaston Avenue, Suite 195\n Dallas, TX 75202',
phone: '469.764.7100',
},
{
key: 1,
name: 'Courtyard Pharmacy',
type: 'Urgent Care Center - 4.09 mi',
location: '5236 West University Drive, Suite 1900\n MCKINNEY, TX 75071',
phone: '969.264.7190',
},
{
key: 2,
name: 'Outptaient Pharmacy at the Cancer Center',
type: 'Urgent Care Center - 4.66 mi',
location: '3800 Gaylord Parkway, Ste 110\n FRISCO, TX 75034',
phone: '890.664.8130',
},
{
key: 3,
name: 'Carrolton Pharmacy',
type: 'Urgent Care Center - 4.08 mi',
location: '5236 West University Drive, Suite 1900\n MCKINNEY, TX 75071',
phone: '969.264.7190',
},
{
key: 4,
name: 'Garland Pharmacy',
type: 'Urgent Care Center - 22.11 mi',
location: '3417 Gaston Avenue, Suite 195\n Dallas, TX 75202',
phone: '469.764.7100',
},
];
I am exporting this const PHARMACY and importing it in my class and set this to a state variable "data".

you can do something like this in renderItem
renderItem = ({item, index}) => {
.....
<RadioButton
innerColor={Colors.darkBlue}
outerColor={Colors.lightGray}
animation={'bounceIn'}
isSelected={this.state.selectedIndex === index}
onPress={() => {this.onPress(index)}}
/>
}
and replace onPress with
onPress = (index) => {
this.setState({ selectedIndex: index });
}
and update FlatList with extraData props as FlatList needs to be re-rendered as
<FlatList
keyExtractor={this._keyExtractor}
data={this.state.data}
renderItem={this.renderItem}
ItemSeparatorComponent={this.renderSeparator}
extraData={this.state}
/>
You can refer in snack here

First, you need to get the index of the current item like so:
const { item, index } = data;
After you get the index of the current item you can then check if the current radio button is selected or not and for changing the radio button you need to pass the value of the current index to the onPress function.
<RadioButton
innerColor={Colors.darkBlue}
outerColor={Colors.lightGray}
animation={'bounceIn'}
isSelected={this.state.selected === index}
onPress={() => this.onPress(index)}
/>

Related

Dynamic textinput inside Flatlist State update

From the sample code below i am trying to render textbox along with content inside Flatlist renderItem method and simultaneously trying to update textbox value.
Bad luck is on device after typing a single character, keyboard goes down.
Please find relevant Snack expo at : https://snack.expo.io/BJGMscqsS
Here is code :
import * as React from "react";
import {
View,
Text,
FlatList,
TextInput
} from "react-native";
export default class App extends React.Component {
state = {
data: []
};
updateItem = async (index, innerindex, itemAttributeVal) => {
console.log(index, innerindex, itemAttributeVal);
console.log(this.state.data);
let { data } = this.state;
data[index][innerindex].Value = itemAttributeVal;
this.setState({
data
});
console.log("newtry", this.state.data);
};
componentDidMount = async () => {
const listdata =
{
totalRow: "2",
coddindata: [
{
"SNo": "1",
"Item": "10",
"Material Code": "SERVICE LABOUR1",
"Invoice Description": "Labour for Services1",
"Invoice Item Amt": "765000.00",
"Approved Quantity": "85",
},
{
"SNo": "2",
"Item": "20",
"Material Code": "SERVICE LABOUR1",
"Invoice Description": "Labour for Services2",
"Invoice Item Amt": "810000.00",
"Approved Quantity": "90",
}
]
}
;
const codingData = listdata.coddindata;
var finalarr = [];
var finalarr1 = [];
codingData.map(datavalue => {
finalarr1 = [];
Object.keys(datavalue).map((key, val) => {
finalarr1.push({ Key: key, Value: datavalue[key] });
});
finalarr.push(finalarr1);
});
this.setState({
data: [...this.state.data, ...finalarr],
totalCount: listdata.totalRow
});
console.log(this.state.data);
};
render() {
return (
<View style={{ flex: 1,padding: 20}}>
<FlatList
style={{ padding: 20 }}
data={this.state.data}
renderItem={({ item, index }) =>
item.map((element, innerindex) => {
// console.log(" innerindex ",innerindex);
const inputstateval = this.state.data[index][innerindex].Value;
return (
<View
key={Math.random().toString()}
style={{
alignItems: "center",
height: 30,
justifyContent: "center",
flexDirection: "row",
lineHeight: 4
}}
>
<View style={{ flex: 1, alignSelf: "stretch" }}>
<Text>{element.Key}</Text>
</View>
{/* { element.Key != "total_amount" ? */}
{element.Key !== "Approved Quantity" ? (
<View
style={{ flex: 2, alignSelf: "stretch", marginTop: 3 }}
>
<Text>{element.Value}</Text>
</View>
) : (
<View
style={{ flex: 2, alignSelf: "stretch", marginTop: 3 }}
>
<TextInput
// defaultValue={element.Value}
placeholder={element.Key}
onChangeText={text => {
console.log("in onChangeText--- ");
this.updateItem(index, innerindex, text);
}}
value={this.state.data[index][innerindex].Value}
style={{
paddingTop: 1,
fontSize: 16,
borderWidth: 1,
height: 30,
marginTop: -6
}}
/>
</View>
)}
</View>
);
})
}
keyExtractor={item => Math.random().toString()}
/>
</View>
);
}
}
In your code, you just need to fix the lines 87, and 132 to something like this:
87: key={'key'}
132: keyExtractor={(item) => ''+item}
So react knows that even after render, those text inputs are the same as the ones before the setState update.
Still, I cant manage to fix this same bug in my project.

FlatList show according to TextInput handle

I have Dynamic form in which user can add form and remove form when user start typing on first form TextInput it will give suggestion as per input. Now the problem is when user start typing on first TextInput field it will get suggestion but when user add another form by clicking on addForm Button and when user start typing on new form it will get suggestion but on same time in the first form it also start giving suggestion and same if there is three form it will start giving suggestion for all three form if user start typing in one form.I want to say that If user type any of form it will give suggestion on all form.
I want like if user is on first form then it will give suggestion only for first form not for second form as well. if user is on second form it will only get suggestion on second form not on first as well.
You can see in above picture it is giving suggestion for both form even if I'm typing on second form
import React, { PureComponent } from 'react'
import {
View,
TextInput,
ScrollView,
KeyboardAvoidingView,
StyleSheet,
Picker,
ListView,
FlatList
} from 'react-native'
import { getStockItems } from "../../actions/getIndentsAction";
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { TouchableOpacity } from 'react-native-gesture-handler';
import { CardSection, Text, Button, Block, Input } from '../../components';
import { theme } from '../../constants';
import { MaterialIcons,AntDesign,Entypo } from '#expo/vector-icons';
import { CardItem,Content, ListItem,Icon,Card, Left, Body, Right } from 'native-base';
class IndentForm extends PureComponent {
static navigationOptions = ({ navigation }) => {
const { params = {} } = navigation.state;
return {
headerRight: (
<TouchableOpacity onPress={() => params.handleSave()}>
<AntDesign
name='plus'
style={{ paddingRight:10}}
size={25}
color='white'
/>
</TouchableOpacity>
)
};
};
constructor(props) {
super(props);
this.state = {
companyName:'',
formFields:[{
Item_Description:'',
Quantity:'',
}],
searchedForm:[]
};
}
componentDidMount() {
this.props.navigation.setParams({ handleSave: this.addInput});
this.props.getStockItems()
}
//add dynamic form
addInput = () => {
const existingFormFields = this.state.formFields.map(fields => ({...fields}))
const allFormFieldsAfterAddingNew = [...existingFormFields, {Item_Description: '', Quantity:''}]
this.setState({formFields: allFormFieldsAfterAddingNew})
}
//remove dynamic form
removeInput = index => () => {
this.setState({
formFields: this.state.formFields.filter((s, sidx) => index !== sidx)
});
};
//on Item Descriptionchange
onItemDescriptionChange = (text, index) => {
const { stocks } = this.props.indent;
const existingFormFields = this.state.formFields.map(fields => ({...fields}))
let targetField = {...existingFormFields[index]}
targetField.Item_Description = text
existingFormFields[index] = targetField
var searchedForm = stocks.filter(function(stock) {
return stock.Item.toLowerCase().indexOf(text.toLowerCase()) > -1;
});
this.setState({searchedForm: searchedForm , formFields: existingFormFields})
}
//on Quantity change
onQuantityChange = (text, index) => {
const existingFormFields = this.state.formFields.map(fields => ({...fields}))
let targetField = {...existingFormFields[index]}
targetField.Quantity = text
existingFormFields[index] = targetField
this.setState({formFields: existingFormFields})
}
itemSelect = (item,index) => {
const existingFormFields = this.state.formFields.map(fields => ({...fields}))
let targetField = {...existingFormFields[index]}
targetField.Item_Description = item.Item
existingFormFields[index] = targetField
this.setState({searchedForm:[], formFields:existingFormFields})
console.log("hello" + " " + item.Item + " " + index);
}
onsubmit = () => {
const data = {
companyName:this.state.companyName,
formFields:this.state.formFields
}
console.log(data)
}
render() {
const { stocks } = this.props.indent;
return (
<KeyboardAvoidingView style={{flex:1, justifyContent:"center"}} behavior="padding">
<ScrollView
showsVerticalScrollIndicator={false}
>
<Block padding={[5]}>
<Card>
<Picker
style={{flex:1}}
selectedValue={this.state.companyName}
onValueChange={(companyName)=>this.setState({companyName:companyName})}
>
<Picker.Item label='developer' value="0" />
<Picker.Item label="Developer" value="Developer" />
<Picker.Item label="Junior Develope" value="Junior Develope" />
</Picker>
</Card>
{
this.state.formFields.map((field, index) => {
return(
<Card key={index} >
<CardItem bordered>
<Left>
<Text bold>Items no : {index + 1}</Text>
</Left>
<Right>
<TouchableOpacity
onPress={this.removeInput(index)}
>
<Entypo
name="cross"
size={20}
color='#E46932'
/>
</TouchableOpacity>
</Right>
</CardItem>
<Block padding={[0, theme.sizes.base]}>
<Block>
<Input
label="description"
style={[styles.input]}
value={field.Item_Description}
onChangeText={(text)=> this.onItemDescriptionChange(text, index)}
/>
<FlatList
data={this.state.searchedForm}
keyExtractor={(ItemId,index) => index.toString()}
renderItem={({item,index})=>(
<ListItem
button={true}
key={index}
onPress={()=>this.itemSelect(item,index)}
>
<Text bold>{item.Item}</Text>
</ListItem>
)}
/>
</Block>
<Input
label="Quantity"
style={[styles.input]}
value={field.Quantity}
onChangeText={(text)=> this.onQuantityChange(text, index)}
/>
</Block>
</Card>
)
})
}
<Block padding={[0, theme.sizes.base * 1.5]}>
<Button
style={styles.submitInput}
onPress={this.onsubmit}>
<Text bold white center>Submit</Text>
</Button>
</Block>
</Block>
</ScrollView>
</KeyboardAvoidingView>
)
}
}
IndentForm.propTypes = {
getStockItems: PropTypes.func.isRequired,
indent: PropTypes.object.isRequired,
};
const mapStateToProps = state => ({
indent: state.indent,
errors:state.errors
});
export default connect(
mapStateToProps,
{
getStockItems,
}
)(IndentForm);
const styles = StyleSheet.create({
input: {
borderRadius: 0,
borderWidth: 0,
borderBottomColor: theme.colors.gray2,
borderBottomWidth: StyleSheet.hairlineWidth,
marginLeft:5
},
submitInput:{
backgroundColor:"#2ecc71"
},
addInput:{
backgroundColor:"white"
},
addButton:{
alignItems:"flex-end",
position:"absolute",
right:20,
bottom:20,
},
searchBarContainerStyle: {
marginBottom: 10,
flexDirection: "row",
height: 40,
shadowOpacity: 1.0,
shadowRadius: 5,
shadowOffset: {
width: 1,
height: 1
},
backgroundColor: "rgba(255,255,255,1)",
shadowColor: "#d3d3d3",
borderRadius: 10,
elevation: 3,
marginLeft: 10,
marginRight: 10
},
selectLabelTextStyle: {
color: "#000",
textAlign: "left",
width: "99%",
padding: 10,
flexDirection: "row"
},
placeHolderTextStyle: {
color: "#D3D3D3",
padding: 10,
textAlign: "left",
width: "99%",
flexDirection: "row"
},
dropDownImageStyle: {
marginLeft: 10,
width: 10,
height: 10,
alignSelf: "center"
},
pickerStyle: {
marginLeft: 18,
elevation:3,
paddingRight: 25,
marginRight: 10,
marginBottom: 2,
shadowOpacity: 1.0,
shadowOffset: {
width: 1,
height: 1
},
borderWidth:1,
shadowRadius: 10,
backgroundColor: "rgba(255,255,255,1)",
shadowColor: "#d3d3d3",
borderRadius: 5,
flexDirection: "row"
}
})
when you do addInput, it adds new FlatList for each input. but, data of FlatList is managed by single state which is this.state.searchedForm.
So whenever onItemDescriptionChange gets called, it updates the searchedForm state and all the FlatList reflects that change.
To resolve this, either you'll have to keep the FlatList data inside formFields state as one key or you can manage different state for each input.

How to show 2 items in one pagination of react native snap carousel

How to dispaly 2 items for one pagination(first dot) and if we swipe then next 2 items should display with showing second dot active.
And if it is odd then last item should display my own component in react native snap carousel.
I would suggest that you go ahead and make the item you're rendering in the Carousel one that renders 2 things at once. The Carousel will paginate on whatever you pass to it, so if you're passing something with 2 items in it, it'll paginate on that, so for example:
<Carousel
layout="default"
data={arr}
renderItem={
({ item, index }) => (
<View style={styles.imageWrapper}>
<Image
style={styles.image}
source={item[0]}
resizeMode="cover"
accessibilityLabel="thumbnail"
/>
<Image
style={styles.image}
source={item[1]}
resizeMode="cover"
accessibilityLabel="thumbnail"
/>
</View>
)
}
lockScrollWhileSnapping={true} // Prevent the user from swiping again while the carousel is snapping to a position.
sliderWidth={screenWidth}
sliderHeight={screenWidth * 0.5}
itemWidth={screenWidth - 40}
activeSlideOffset={50}
enableSnap
onSnapToItem={onSnapToItem}
removeClippedSubviews={false}
firstItem={0}
contentContainerCustomStyle={styles.style}
/>
Create a function that split "entries" array into smaller arrays based on the size that you want
var slides = [];
const entriesSplitter = () => {
let size = 2; //Based on the size you want
while (entries.length > 0) {
slides.push(entries.splice(0, size));
}
};
then pass the slides array to <Carousel data={slides}/> then render each slide
in _renderItem
consider the following example:-
import React, { useState, useRef } from "react";
import { View,Text, Dimensions } from "react-native";
import Carousel, { Pagination } from "react-native-snap-carousel";
const { width: screenWidth, height: screenHeight } = Dimensions.get("window");
const myCarousel = () => {
const [activeSlide, setActiveSlide] = useState(0);
const carousel = useRef();
const entries = [
{
title: "Adidas"
},
{
title: "Nike"
},
{
title: "Puma"
},
{
title: "Reebok"
}
];
var slides = [];
const entriesSplitter = () => {
let size = 2; //Based on the size you want
while (entries.length > 0) {
slides.push(entries.splice(0, size));
}
};
// render every single slide
const _renderItem = ({ item,index }) => {
return (
<View style={{ flexDirection: "row", flexWrap: "wrap" }}>
{item.map(item => {
return <Text key={index}>{item.title}</Text>;
})}
</View>
);
};
return (
<View>
{entriesSplitter()}
<Carousel
ref={carousel}
data={slides}
renderItem={_renderItem}
onSnapToItem={index => setActiveSlide(index)}
sliderWidth={screenWidth}
sliderHeight={screenHeight}
itemWidth={screenWidth}
/>
<Pagination
dotsLength={2} // also based on number of sildes you want
activeDotIndex={activeSlide}
containerStyle={{ backgroundColor: "red", borderWidth: 2 }}
dotStyle={{
width: 10,
height: 10,
borderRadius: 5,
marginHorizontal: 8,
backgroundColor: "black"
}}
inactiveDotStyle={{
backgroundColor: "pink"
}}
inactiveDotOpacity={0.4}
inactiveDotScale={0.6}
/>
</View>
);
};
export default myCarousel;
This is how I implemented to show 3 carousels. We can customize it in many ways
import React from "react";
import { View, Dimensions, StyleSheet, Image } from "react-native";
import Carousel from "react-native-snap-carousel";
const windowWidth = Dimensions.get("window").width;
export default function MyCarousel() {
const images = [
{ id: 1, image: require("../assets/home-slider-1.jpg") },
{ id: 2, image: require("../assets/home-slider-2.jpg") },
{ id: 3, image: require("../assets/home-slider-3.jpg") },
{ id: 4, image: require("../assets/home-slider-4.jpg") }
];
// const imagesUri = [
// { id: 1, image: { uri: 'https://i.imgur.com/gG5Egof.jpg' } },
// { id: 2, image: { uri: 'https://i.imgur.com/gG5Egof.jpg' } },
// { id: 3, image: { uri: 'https://i.imgur.com/gG5Egof.jpg' } },
// { id: 4, image: { uri: 'https://i.imgur.com/gG5Egof.jpg' } }
// ];
const _renderItem = ({ item }) => {
return (
<View style={styles.slide}>
<Image
source={item.image}
style={styles.image}
// resizeMode="center"
></Image>
</View>
);
};
return (
<View style={styles.wrapper}>
<Carousel
data={images}
renderItem={_renderItem}
sliderWidth={windowWidth}
itemWidth={windowWidth - 70}
enableMomentum={false}
lockScrollWhileSnapping
autoplay
useScrollView
loop
autoplayInterval={3000}
/>
</View>
);
}
const styles = StyleSheet.create({
wrapper: {
height: 150
},
slide: {
flex: 1,
justifyContent: "center",
alignItems: "center",
backgroundColor: "#fff"
},
image: {
flex: 1,
height: "100%",
width: "100%",
alignItems: "center",
justifyContent: "center"
}
});

ListView doesn't scroll

I have a horizontal ListView (shown in the image with list items a,b,c) that will not scroll, or rather, it does scroll - but one out of 10 or so swipes seems to make it scroll. I have also used a FlatList - same result. The ListView is on a Interactable.View, however I got rid of the Interactable.View and it still didn't scroll. I've tested on a real ios device and a genymotion emulator and both had the same result. There are more items in the list than just a,b,c. There are 6 items in the list.
import { StyleSheet, View, Text, FlatList, ListView } from 'react-native'
import React, { Component } from 'react'
import MapView from 'react-native-maps'
import { connect } from 'react-redux'
import {
Button,
Container
} from 'native-base'
import { updateRegion } from './map.action'
import { OptimizedFlatList } from 'react-native-optimized-flatlist'
import Icon from 'react-native-vector-icons/FontAwesome'
import { toggleMenu } from '../search-page/searchPage.action'
import mapStyle from './style'
import Interactable from 'react-native-interactable'
import { setSelectedShop } from '../search-results/searchResults.action'
import { updateHeight } from '../search-results/searchResultsPresenter.action'
import { getSelectedProduct } from './markers.selector'
const mapStateToProps = (state) => ({
region: state.get('map').get('region'),
markers: state.get('searchResults').get('products'),
selectedProduct: getSelectedProduct(state),
height: state.get('searchResultsPresenter').get('height')
})
const mapDispatchToProps = (dispatch) => ({
onRegionChange: (region) => {
dispatch(updateRegion(region))
},
onToggleMenuClick: () => {
dispatch(toggleMenu())
},
setSelectedShop: id => {
dispatch(setSelectedShop(id))
},
updateHeight: height => {
dispatch(updateHeight(height))
}
})
class Map extends Component {
componentDidMount() {
const { store } = this.context
this.unsubscribe = store.subscribe(() => { })
}
componentWillUnmount() {
this.unsubscribe()
}
componentWillReceiveProps(newProps) {
if (newProps.selectedProduct) {
let products = newProps.selectedProduct.products
this.setState({
dataSource: this.state.dataSource.cloneWithRows(products)
})
}
}
interactableView;
constructor(props) {
super(props)
this.state = { dataSource: new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 }) }
}
render() {
console.log(this.props.height)
return (
<Container>
<MapView
style={styles.map}
region={this.props.region}
onRegionChangeComplete={this.props.onRegionChange}>
{
this.props.markers.map(marker => {
return (
<MapView.Marker
coordinate={marker.shop.coordinate}
title={marker.shop.name}
identifier={marker.shop.id.toString()}
onPress={e => {
console.log(e.nativeEvent)
this.interactableView.snapTo({ index: 0 })
this.props.setSelectedShop(marker.shop)
console.log(this.props.selectedProduct)
}}
/>
)
})
}
</MapView>
<Button
small
icon
style={mapStyle.toggleMenuButton}
onPress={() => this.props.onToggleMenuClick()}>
<Icon name="sliders" size={20} color="#FFFFFF" />
</Button>
<Interactable.View
style={{
flex: 1,
flexDirection: 'row',
zIndex: 20,
borderRadius: 10,
backgroundColor: '#222222',
padding: 30,
paddingTop: 50
}}
verticalOnly={true}
snapPoints={[{ y: this.props.height - 225 }, { y: this.props.height - 50 }]}
initialPosition={{ y: this.props.height - 50 }}
ref={view => this.interactableView = view}
onLayout={(event) => {
this.props.updateHeight(event.nativeEvent.layout.height)
}} >
<View style={{ flex: 1, flexDirection: 'row', height: 50 }}>
<Text
style={{
color: 'white',
position: 'absolute',
top: -40,
marginBottom: 20,
textAlign: 'center',
width: '100%'
}}>
{this.props.selectedProduct ? this.props.selectedProduct.shop.name : ''}
</Text>
<ListView
dataSource={this.state.dataSource}
horizontal={true}
style={{
height: 200
}}
renderRow={(rowData)=> {
console.log(rowData)
return (
<View style={{
backgroundColor: 'blue',
width: 100,
borderWidth: 1,
borderColor: 'black',
margin: 0
}}>
<Text style={{ color: 'white' }}>{rowData.name}</Text>
<View style={{
zIndex: 15,
width: '100%',
height: '100%',
backgroundColor: 'red'
}}>
</View>
</View>
)
}}
/>
</View>
</Interactable.View>
</Container>
)
}
}
Map.contextTypes = {
store: React.PropTypes.object
}
Map.propTypes = {
region: React.PropTypes.shape({
latitude: React.PropTypes.number,
longitude: React.PropTypes.number,
latitudeDelta: React.PropTypes.number,
longitudeDelta: React.PropTypes.number
}).isRequired,
height: React.PropTypes.number,
updateHeight: React.PropTypes.func,
setSelectedShop: React.PropTypes.func,
selectedProduct: React.PropTypes.string,
onRegionChange: React.PropTypes.func.isRequired,
onToggleMenuClick: React.PropTypes.func.isRequired,
markers: React.PropTypes.array
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(Map)
const styles = StyleSheet.create({
map: {
...StyleSheet.absoluteFillObject,
zIndex: 3
}
})
How do I get the listview to scroll with every swipe, rather than about 1 out of 10 swipes?
Same thing happens when I use a ScrollView. So nothing can be swiped horizontally there. Even when removing the interactable.view
Making renderRow return a TouchableHighlight instead of a View caused the list to be draggable with every touch and swipe. And finally, unessential to the answer, I switched from a ListView to a FlatList because ListView is going to be deprecated in the future. I felt it good to state that as at this point in time it isn't clear from the official documentation that ListView is becoming deprecated.

error "objects are not valid as a react child" in react native

"objects are not valid as a react child (found: object with keys {date, events}). If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons. Check the render method of View."
So I have kind of a cascade of method calls. I'm retrieving dates with events inside of those. It feels like I'm doing this correctly, but am getting the above error. I've tried setting createFragment on places, but still getting the error. Here's the code:
import React, { Component } from 'react';
import {
AppRegistry,
Text,
View,
ScrollView,
RefreshControl,
StyleSheet,
Dimensions,
TextInput,
Linking,
TouchableNativeFeedback
} from 'react-native';
var _ = require('lodash');
var {width, height} = Dimensions.get('window');
var renderif = require('render-if');
var createFragment = require('react-addons-create-fragment');
var IMAGES_PER_ROW = 1
class FunInATL extends Component {
constructor(props) {
super(props);
this.state = {
currentScreenWidth: width,
currentScreenHeight: height,
dates: [],
boxIndex: 0,
showBox: false,
refreshing: false
};
}
handleRotation(event) {
if (!this.state) {
return;
}
var layout = event.nativeEvent.layout
this.state({currentScreenWidth: layout.width, currentScreenHeight: layout.height })
}
calculatedSize() {
var size = this.state.currentScreenWidth / IMAGES_PER_ROW
return {width: size}
}
renderRow(events) {
return events.map((events, i) => {
return (
<Image key={i} style={[this.getImageStyles(), styles.image, this.calculatedSize() ]} source={{uri: event.image}} />
)
})
}
openUrl(url) {
Linking.canOpenURL(url).then(supported => {
if (supported) {
Linking.openURL(url);
} else {
console.log('nope :: ' + url);
}
}).catch(err => console.error('An error occurred', err));
}
getImageStyles(featured, category) {
let options = {
borderColor: 'gold',
borderWidth: featured ? 1 : 0
}
if (!category) {
options.height = featured ? 250 : 125
}
return options;
}
_clickImage(event, index) {
if (event.title) {
let new_val = !this.state.showBox
this.setState({
dates: this.state.dates,
showBox: new_val,
boxIndex: new_val ? index : 0
});
}
}
componentDidMount() {
this.state = {
dates: [],
boxIndex: 0,
showBox: false,
refreshing: false
};
this.getApiData();
Linking.addEventListener('url', this.handleUrl);
}
componentWillUnmount() {
Linking.removeEventListener('url', this.handleUrl);
}
getApiData() {
var _this = this;
return fetch('https://www.funinatl.com/mobile2.php?v1')
.then(function(response) {
return response.json()
})
.then((responseJson) => {
var dates = createFragment(responseJson.events)
return;
let _this = this;
date.events.map((event, i) => (
date.events[i] = event
))
var datesData = [];
dates.map((date, i) => (
datesData.push({
date: i,
events: createFragment(date.events)
})
))
_this.setState({
dates: createFragment(datesData),
boxIndex: 0,
showBox: false
})
console.error(this.state);
})
.catch((error) => {
console.error(error);
})
.done();
}
renderDates() {
return this.state.dates.map((date) =>
(
<View>
<Text style={styles.dateHeader}>{ date.date }</Text>
<View>
{this.renderEvents(date.events)}
</View>
</View>
))
}
renderImage(event, index) {
if (this.state.showBox && this.state.boxIndex == index) {
return (
<View>
<TouchableNativeFeedback onPress={()=>this._clickImage(event, index)}>
<Image source={{ uri: event.image }} style={[styles.image, this.calculatedSize(), this.getImageStyles(event.featured), { height: 100 }]} />
</TouchableNativeFeedback>
<View style={{ flexDirection:'row', padding: 15 }}>
<Text style={styles.price}>{event.price}</Text>
<Text style={styles.time}>{event.time}</Text>
<TouchableNativeFeedback onPress={()=>this.openUrl(event.website)}>
<Text style={styles.btn}>Website</Text>
</TouchableNativeFeedback>
</View>
{renderif(event.venue)(
<TouchableNativeFeedback onPress={()=>this.openUrl(event.venue)}>
<Text style={styles.btn}>Venue</Text>
</TouchableNativeFeedback>
)}
</View>
)
} else {
return (
<View>
<TouchableNativeFeedback onPress={()=>this._clickImage(event, index)}>
<Image source={{ uri: event.image }} style={[styles.image, this.calculatedSize(), this.getImageStyles(event.featured)]} />
</TouchableNativeFeedback>
</View>
)
}
}
renderEvents(events) {
return events.map((event, i) =>
(
<View>
<Text style={[styles.eventCategory, this.getImageStyles(event.featured, true)]}>{event.category}</Text>
<View>
{this.renderImage(event, i)}
</View>
<Text style={[styles.eventTitle, this.getImageStyles(event.featured, true)]}>{event.title}</Text>
</View>
));
}
_onRefresh() {
this.setState({refreshing: true});
fetchData().then(() => {
this.setState({refreshing: false});
});
}
render() {
return (
<ScrollView onLayout={this.handleRotation} contentContainerStyle={styles.scrollView} refreshControl={
<RefreshControl
refreshing={this.state.refreshing}
onRefresh={this._onRefresh.bind(this)}
tintColor="#ff0000"
title="Loading..."
titleColor="#00ff00"
colors={['#ff0000', '#00ff00', '#0000ff']}
progressBackgroundColor="#ffff00"
/>
}>
<Text style={styles.header}>FunInATL</Text>
{this.renderDates()}
</ScrollView>
)
}
}
var styles = StyleSheet.create({
row: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'flex-start',
textAlign: 'center',
padding: 10
},
header: {
fontSize: 30,
fontWeight: 'bold',
padding: 20,
textAlign: 'center',
backgroundColor: '#000',
color: '#fff'
},
dateHeader: {
fontSize: 20,
fontWeight: 'bold',
padding: 20,
textAlign: 'left',
color: '#fff',
backgroundColor: '#283593'
},
eventCategory: {
backgroundColor: '#03a9f4',
textAlign: 'center',
color: '#ffffff',
padding: 3
},
eventTitle: {
borderTopWidth: 0,
textAlign: 'center',
fontWeight: 'bold',
padding: 3,
fontSize: 18,
},
image: {
},
btn: {
backgroundColor: 'green',
padding: 10,
color: '#fff',
textAlign: 'center',
flex: 1
},
price: {
marginLeft: 10,
fontSize: 16,
flex: 1
},
time: {
marginRight: 10,
fontSize: 16,
flex: 1,
width: 35
}
});
AppRegistry.registerComponent('FunInATL', () => FunInATL);
Thanks!
EDIT: Updated code per the map suggestion, still not working. complaining about {events} only now.
EDIT 2: Updated with FULL code.
The component's render helpers, such as renderDates(), are returning _.each(...). _.each() returns its first argument so this is why you are receiving the error.
To illustrate:
const myObject = { a: 1 };
_.each(myObject) === myObject // true
I recommend you use Array.prototype.map() instead:
return this.state.dates.map((date) => (
<View>...</View>
));
If you use arrow functions like I did in the example above, there's no need to save a reference to this. this in the body of the function passed to map() will be bound to the instance of the component. You can then call other helper methods such as getImageStyles() like this.getImageStyles(...).
This is not related to your original question but the getApiData() method will not work. You can replace the function in the chain that handles responseJson with something like:
(responseJson) => {
this.setState({
dates: Object.entries(responseJson.events).map(([date, { events }]) => ({
date,
events,
})),
boxIndex: 0,
showBox: false,
});
}
You also need to to remove the this.state = {...} in componentDidMount(). Notice the warning in the docs that indicates you should "NEVER mutate this.state directly".