React native flatlist can't render 20 items at ones - android

I have 20 JSON data set that get using the fetch method and show that in flatlist.
My issue is when I load that data and scroll to the end of list, it scrolls til 13th data only. 7 data won't show. My flatlist does not scroll the end of the data set.
I was attache my screenshot and my source code. if anyone can help me with this issue. is a big help for me. Thanks
Is there any limit flatlist rendering??
class CategoryList extends Component{
constructor(props) {
super(props);
this.state={
info: [],
isLoading: true
};
}
static navigationOptions = {
header: {
visible: false,
}
}
handlePress = async () => {
fetch('http://209.97.172.234/index.php/testCV/jobCatogoryList', {
method: 'POST',headers: {
'Content-Type': 'application/json',
}
})
.then((response) => response.json())
.then((responseJson) => {
this.setState({ info: responseJson.data});
})
.catch((error) => {
console.error(error);
});
}
componentDidMount(){
this.handlePress();
}
render() {
const { info } = this.state;
return (
<View>
<Header>
<TouchableHighlight onPress={() => this.props.navigation.toggleDrawer()} >
<MyCustomLeftComponent />
</TouchableHighlight>
<MyCustomCenterComponent name='Category' />
<MyCustomRightComponent />
</Header>
<Card containerStyle={[styles.cardContainer]} >
<SearchBar
lightTheme
placeholder='Type Here...' />
<View>
<FlatList
data={info.cList}
renderItem={({ item }) => (
<ListItem
title={item.cName}
badge={{ value: item.cCount, textStyle: { color: 'orange' }}}
/>
)}
/>
</View>
</Card>
</View>
);
}
}

Related

React native mapbox-gl crashes with react-navigation

I have a problem. When I display a map with #rnmapbox/maps and that I want to navigate in my screens, the app freeze then crashes. I'm pretty sure that this is a rnmapbox problem because when I remove the code between <MapboxGL.MapView> and <MapboxGL.MapView/>, navigation works fine.
I use #react-navigation/native and #react-navigation/native-stack
Note that this issus don't append on iOS, only on Android.
Record of the issue : https://vimeo.com/723749736
Here is my code :
App.js
import React from 'react';
import MapScreen from './src/screens/MapScreen';
import PlaceDetailsScreen from './src/screens/PlaceDetailsScreen';
import VideoPlayerScreen from './src/screens/VideoPlayerScreen';
import {createNativeStackNavigator} from '#react-navigation/native-stack';
import {NavigationContainer} from '#react-navigation/native';
import {SafeAreaProvider} from 'react-native-safe-area-context';
import {GestureHandlerRootView} from 'react-native-gesture-handler';
function App() {
const Stack = createNativeStackNavigator();
return (
<SafeAreaProvider>
<GestureHandlerRootView style={{flex: 1}}>
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen
name="Map"
component={MapScreen}
options={{headerShown: false}}
/>
<Stack.Group>
<Stack.Screen name="Details" component={PlaceDetailsScreen} />
<Stack.Screen
name="VideoPlayer"
component={VideoPlayerScreen}
options={{headerShown: false}}
/>
</Stack.Group>
</Stack.Navigator>
</NavigationContainer>
</GestureHandlerRootView>
</SafeAreaProvider>
);
}
export default App;
MapScreen.js
import React, {useState, useRef, useMemo, useCallback, useEffect} from 'react';
import {View, Text, PermissionsAndroid, Platform} from 'react-native';
import MapboxGL from '#rnmapbox/maps';
import BottomSheet, {BottomSheetScrollView} from '#gorhom/bottom-sheet';
import Styles from '../../Styles';
import PlaceBtn from '../components/PlaceBtn/PlaceBtn';
import IconPin from './../assets/icons/icon-locationPin.svg';
MapboxGL.setAccessToken(
'XXXXXXXXXXXXXXXXXXXXXXXXXXX',
);
function MapScreen({navigation}) {
const [hasGeolocPermission, setHasGeolocPermission] = useState(false);
const [currentRegion, setCurrentRegion] = useState([4.824, 45.76]); //longitude, latitude
const [userLocation, setUserLocation] = useState();
const [nearestPoints, setNearestPoints] = useState([]);
const markers = require('../data/markers.json');
const route = require('../data/route.json');
const routeLine = {
type: 'FeatureCollection',
features: [
{
type: 'Feature',
properties: {},
geometry: {
type: 'LineString',
coordinates: route.points,
},
},
],
};
const bottomSheetRef = useRef(null);
const snapPoints = useMemo(() => ['13%', '75%', '100%'], []);
const handleSheetChanges = useCallback(index => {
console.log('handleSheetChanges', index);
}, []);
const requestLocationPermission = async () => {
if (Platform.OS === 'android') {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
);
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
console.log('location uses is granted');
setHasGeolocPermission(true);
} else {
console.log(granted);
console.log('location access denied');
}
} catch (error) {
console.warn('error while request location : ', error);
}
}
};
useEffect(() => {
requestLocationPermission();
}, []);
return (
<View style={Styles.container}>
<MapboxGL.MapView style={Styles.map} scaleBarEnabled={false}>
<MapboxGL.UserLocation
animated
showsUserHeadingIndicator
minDisplacement={1}
onUpdate={position => {
console.log('position : ', position);
}}
/>
<MapboxGL.Camera centerCoordinate={currentRegion} zoomLevel={14} />
{markers.map((marker, index) => {
if (marker.category === 'introduction') {
console.log('intro');
} else {
return (
<MapboxGL.PointAnnotation
key={index}
id={marker.id + ''}
coordinate={[marker.longitude, marker.latitude]}>
<IconPin width={35} height={35} fill={'#00c0aa'} />
</MapboxGL.PointAnnotation>
);
}
})}
<MapboxGL.ShapeSource id="line1" shape={routeLine}>
<MapboxGL.LineLayer
id="linelayer1"
style={{lineColor: 'red', lineWidth: 5}}
/>
</MapboxGL.ShapeSource>
</MapboxGL.MapView>
<BottomSheet
ref={bottomSheetRef}
handleIndicatorStyle={Styles.handleIndicator}
index={0}
snapPoints={snapPoints}
onChange={handleSheetChanges}>
<View style={Styles.bottomSheetContent}>
<Text style={Styles.bottomSheetTitle}>{route.name}</Text>
<BottomSheetScrollView>
{markers.map((place, index) => {
return (
<PlaceBtn
place={place}
navigation={navigation}
//isNear={nearestPoints.includes(place.id)}
/>
);
})}
</BottomSheetScrollView>
</View>
</BottomSheet>
</View>
);
}
export default MapScreen;
PlaceDetailsScreen.js
import React from 'react';
import {View, Text, TouchableOpacity} from 'react-native';
function PlaceDetailsScreen({navigation}) {
return (
<>
<TouchableOpacity
style={{backgroundColor: '#00FF00'}}
onPress={() => navigation.navigate('Map')}>
<Text>Go to MAP</Text>
</TouchableOpacity>
<TouchableOpacity
style={{backgroundColor: '#00FF00'}}
onPress={() => navigation.navigate('VideoPlayer')}>
<Text>Go to Video Player</Text>
</TouchableOpacity>
</>
);
}
```
I had the same problem. In my case I have a modal that is persistent through all screens and that modal shrinks when user swipes down like in youtube. After I initialized map inside modal, whenever I try to change screen my app were first freezing then crashing.
My solution was to render map only when modal is expanded. So I made a conditional rendering. Checked whether modal is shrinked or not. If shrinked, then render the map, else don't render. Thus my navigation worked without any problem.
This was my case and that's how I solved it:
// I use reduxjs toolkit.
// Since this modal is gonna be persistent through all screens
// It's best to store translateY value in redux.
const Modal = useAppSelector((state) => state.Modal);
const translateY = useSharedValue(Modal.translateY);
// I watch this variable with an useEffect hook to dynamically update redux value
const [translateYState, setTranslateYState] = useState(translateY.value);
useEffect(() => {
dispatch(setTranslateY(translateYState));
}, [translateYState]);
// translateYState's value is dynamically updating by a pan gesture detector
// translateYState value to be 0 means modal is expanded and user is using the modal
return (
<>
{translateYState==0 && (
<MapboxGL.MapView style={styles.map}></MapboxGL.MapView>
)}
</>
)
You can un-render the map when the modal which has title "Les Sens de Lyon" expands. If you are worried about your map data, you can store the map data for example all locations of markers in redux to be persistent but if your app is a single page app it should not be a problem else you can use redux.

How to get variable react native

I'm using react native expo for the following project basically i want to retrive the selected item form an flat list and display it in a modal
import React,{ Component}from 'react';
import {View,Text,Image,StyleSheet,Modal,Button} from 'react-native';
import { FlatList, TouchableOpacity, ScrollView } from 'react-native-gesture-handler';
import Card from '../shared/card';
import { AppLoading } from 'expo';
import * as Font from 'expo-font';
export default class MealSearch extends Component{
constructor(props){
super(props)
this.state = {
loaded:false,
show:false,
key:''
}}
render(){
const meal= [ {title:'My hero Academia',img:{uri:'https://i.cdn.turner.com/adultswim/big/img/2018/05/10/MHA_Header.png'}, body:'Rating : 4.5/5' , id :'1'},
{title:'Naruto',img:{uri:'https://store-images.s-microsoft.com/image/apps.15041.71343510227343465.377174a9-abc8-4da3-aaa6-8874fdb9e2f5.00fc0a9e-295e-40ca-a391-58ed9f83e9a0?mode=scale&q=90&h=1080&w=1920&background=%23FFFFFF'}, body:'Rating : 5/5' , id :'2'},
{title:'Attack On Titan',img:{uri:'https://www.denofgeek.com/wp-content/uploads/2013/12/attack-on-titan-main.jpg?fit=640%2C380'}, body:'Rating : 4.5/5' , id :'3'},
{title:'Fate: Unlimited Blade Works',img:{uri:'https://derf9v1xhwwx1.cloudfront.net/image/upload/c_fill,q_60,h_750,w_1920/oth/FunimationStoreFront/2066564/Japanese/2066564_Japanese_ShowDetailHeaderDesktop_496a6d81-27db-e911-82a8-dd291e252010.jpg'}, body:'Rating : 4.5/5' , id :'4'}
]
const handlePress = (meal_data) =>{
this.setState({show: true});
this.setState({selectedMeal:meal_data});
console.log(meal_data)
}
return(
<View style={styles.view} >
<FlatList
keyExtractor={item => item.id}
data={meal}
renderItem={({item})=>(
<Card>
<TouchableOpacity onPress={(_item)=>{handlePress(item)}}>
<View style={styles.mealItem}>
<Image style={{width:300,height:150}} resizeMode={'contain'} source={item.img} marginLeft={30}/>
<View style={styles.descrip}>
<Text style={styles.rating}>{item.title}</Text>
<Text style={styles.name}>{item.body}</Text>
</View>
</View>
</TouchableOpacity>
</Card>
)}
/>
<Modal
transparent={true}
visible={this.state.show}
>
<View style={styles.modal}>
<View style={styles.inModal}>
<Button title='End' onPress={()=>{this.setState({show:false})}}/>
</View>
</View>
</Modal>
</View>
);}
}
this is the code I'm currently working on I want the 'meal_data' in 'handlePress' to be displayed inside my modal 'meal_data' is the selected item from the flat list .
<Modal
transparent={true}
visible={this.state.show}
>
<View style={styles.modal}>
<View style={styles.inModal}>
<Button title='End' onPress={()=>{this.setState({show:false})}}/>
</View>
</View>
</Modal>
I want to display it in here above the button
Change these lines of code:
Change: <TouchableOpacity onPress={(_item)=>{handlePress(item)}}>
To
<TouchableOpacity onPress={() => this.handlePress(item)}>
Delete this code inside render():
const handlePress = (meal_data) =>{
this.setState({show: true});
this.setState({selectedMeal:meal_data});
console.log(meal_data)
}
And put this code above render() medthod instead:
handlePress = (meal_data) =>{
this.setState({show: true, selectedMeal: meal_data});
console.log(meal_data)
}
Inside state
this.state = {
loaded:false,
show:false,
key:''
selectedMeal: null // Add this property
}}
After that, you'll be able to access selectedMeal inside your Modal.
Put this code inside the Modal (or somewhere else)
{this.state.selectedMeal && (
<View>
<Text>{this.state.selectedMeal.title}</Text>
</View>
)}
First of declare your handlePress outside of render method. Other thing is that this.setState() is Async so, first set you data then show the modal. Your final code should look like this :
import React, { Component } from 'react';
import { View, Text, Image, StyleSheet, Modal, Button } from 'react-native';
import { FlatList, TouchableOpacity, ScrollView } from 'react-native-gesture-handler';
import Card from '../shared/card';
import { AppLoading } from 'expo';
import * as Font from 'expo-font';
export default class MealSearch extends Component {
constructor(props) {
super(props)
this.state = {
loaded: false,
show: false,
key: ''
}
}
handlePress = (meal_data) => {
this.setState({ selectedMeal: meal_data }, () => {
this.setState({ show: true });
});
console.log(meal_data)
}
render() {
const meal = [
{ title: 'My hero Academia', img: { uri: 'https://i.cdn.turner.com/adultswim/big/img/2018/05/10/MHA_Header.png' }, body: 'Rating : 4.5/5', id: '1' },
{ title: 'Naruto', img: { uri: 'https://store-images.s-microsoft.com/image/apps.15041.71343510227343465.377174a9-abc8-4da3-aaa6-8874fdb9e2f5.00fc0a9e-295e-40ca-a391-58ed9f83e9a0?mode=scale&q=90&h=1080&w=1920&background=%23FFFFFF' }, body: 'Rating : 5/5', id: '2' },
{ title: 'Attack On Titan', img: { uri: 'https://www.denofgeek.com/wp-content/uploads/2013/12/attack-on-titan-main.jpg?fit=640%2C380' }, body: 'Rating : 4.5/5', id: '3' },
{ title: 'Fate: Unlimited Blade Works', img: { uri: 'https://derf9v1xhwwx1.cloudfront.net/image/upload/c_fill,q_60,h_750,w_1920/oth/FunimationStoreFront/2066564/Japanese/2066564_Japanese_ShowDetailHeaderDesktop_496a6d81-27db-e911-82a8-dd291e252010.jpg' }, body: 'Rating : 4.5/5', id: '4' }
]
return (
<View style={styles.view} >
<FlatList
keyExtractor={item => item.id}
data={meal}
renderItem={({ item }) => (
<Card>
<TouchableOpacity onPress={() => { this.handlePress(item) }}>
<View style={styles.mealItem}>
<Image style={{ width: 300, height: 150 }} resizeMode={'contain'} source={item.img} marginLeft={30} />
<View style={styles.descrip}>
<Text style={styles.rating}>{item.title}</Text>
<Text style={styles.name}>{item.body}</Text>
</View>
</View>
</TouchableOpacity>
</Card>
)}
/>
<Modal
transparent={true}
visible={this.state.show}
>
<View style={styles.modal}>
<View style={styles.inModal}>
<Button title='End' onPress={() => { this.setState({ show: false }) }} />
</View>
</View>
</Modal>
</View>
);
}
}

Get row wise state inside flatlist in react native

I have a flatlist and inside flatlist I Have a radioform. I have 2 items of radioform 'P' and 'A' Here is the picture of that
Here I need to post the selected item.My Problem is if I select P then all row value is P when I post and if I select A all row value is A . I have a logic that I have to get the row id wise state get to post . Here so far I have code
export default class attendancetest extends Component {
constructor(props) {
super(props);
this.state = {
data: [],
rollno:"",
typeofattendance:1,
animating: true
};
}
componentWillMount() {
this.fetchData();
}
fetchData = async () => {
const response = await
fetch("http://192.168.1.208:8082/students/all");
const json = await response.json();
this.setState({ data: json });
};
closeActivityIndicator = () =>
setTimeout(
() =>
this.setState({
animating: false
}),
4000
);
componentDidMount = () => this.closeActivityIndicator();
render() {
const animating = this.state.animating;
return (
<View
style={--Style Code
}
>
<Logo />
<Text style={styles.titleText1}>
Test Section A Class 11th
</Text>
<ActivityIndicator
--Some Code
/>
<View style={styles.container}>
<Text style={styles.titleText}>Roll & Name Present Or Absent</Text>
</View>
<FlatList
data={this.state.data}
// rollno={this.state.data.rollno}
showsVerticalScrollIndicator={false}
renderItem={({ item,index }) => (
<View
style=--Style Code
>
<Text
style=--style code
>
{item.rollno}
--
{item.name}
</Text>
<RadioForm
animation={true}
buttonColor={"#C2E3A9"}
index={1}
formHorizontal={true}
labelHorizontal={true}
buttonStyle={{ marginRight: 20 }}
radioStyle={{ paddingRight: 20 }}
// labelHorizontal={false}
style={{
flex: 1,
paddingRight: 20,
flexDirection: "row",
width: 30
}}
radio_props={radio_props}
initial={this.state.typeofattendance}
// initial={value => {
// this.setState({ value: value });}}
isSelected = {true}
// radio_props
onPress={value => { index=
this.setState({ typeofattendance: value });
}}
ItemSeparatorComponent={this.renderSeparator}
/>
</View>
)}
// keyExtractor={(x, i) => i}
keyExtractor={(item, index) => index.toString()}
/>
<Button title="Submit" onPress={() => this.insert()} />
</View>
);
}
insert = () => {
var numstudent = this.state.data.length;
var datatest=[]
var data1;
for(var i=0;i<numstudent;i++){
data1={"rollno": this.state.data[i].rollno, "typeofattendence":
this.state.typeofattendance};
datatest.push(data1);
}
console.log(datatest);
}
}
Here this portion I can get P to A but not in particular row
</View>
onPress={value => {
this.setState({ typeofattendance: value });
}}
How to get row wise state get inside flatlist .
Here in these portion I check the radiobutton check item in button click
var numstudent = this.state.data.length;
var datatest=[]
var data1;
for(var i=0;i<numstudent;i++){
data1={"rollno": this.state.data[i].rollno, "typeofattendence": this.state.typeofattendance};
datatest.push(data1);
}
// console.log(datatest);

ReactNative FlatList is not rendered properly in Arabic Right To Left

I have a FlatList to display list of users, when I change the device language to arabic, RTL is not rendered correctly. The arrows should be pointing the other way.
Here is the screenshot of how it looks on mobile.
Could you suggest if I am missing anything.
Here is my code.
FlatListScreen.js
import React, {Component} from 'react';
import {View, Text, FlatList} from 'react-native';
import {List, ListItem, SearchBar} from 'react-native-elements';
class FlatListScreen extends Component{
constructor(props) {
super(props);
this.state = {
loading: false,
date: [],
page: 1,
seed: 1,
error: null,
refreshing: false
};
}
componentDidMount(){
this.makeRemoteRequest();
}
makeRemoteRequest = () => {
const {page, seed } = this.state;
const url = 'https://randomuser.me/api/?seed=${seed}&page=${page}&results=20';
this.setState({loading: true});
fetch(url)
.then(res => res.json())
.then(res => {
this.setState({
data: page === 1 ? res.results : [...this.state.data, ...res.results],
error: res.error || null,
loading: false,
refreshing: false
});
})
.catch(error => {
this.setState({error, loading: false});
});
};
renderSeparator = () => {
return (
<View
style={{
height: 1,
width: '86%',
backgroundColor: '#CED0CE',
marginLeft: '14%',
}}
/>
);
};
renderFooter = () => {
if(!this.state.loading) return null;
return (
<View
style={{
paddingVertical: 20,
borderTopWidth: 1,
borderTopColor: "#CED0CE"
}}
/>
)
};
renderHeader = () => {
return <SearchBar
placeholder="Search.."
lightTheme
round />;
}
onLearnMore = (item) => {
this.props.navigation.navigate('Profile', { ...item });
};
render (){
return (
<List containerStyle={{ borderTopWidth: 0, borderBottomWidth: 0}}>
<FlatList
data = {this.state.data}
renderItem={({item}) => (
<ListItem
roundAvatar
title={`${item.name.first} ${item.name.last}`}
subtitle={item.email}
avatar={{uri: item.picture.thumbnail}}
containerStyle={{ borderBottomWidth: 0 }}
onPress={() => this.onLearnMore(item)}
/>
)}
keyExtractor = {item => item.email}
ItemSeparatorComponent={this.renderSeparator}
ListHeaderComponent={this.renderHeader}
ListFooterComponent={this.renderFooter}
/>
</List>
)
}
}
export default FlatListScreen;
From the React-native documentation I have added following code for RTL support
https://facebook.github.io/react-native/blog/2016/08/19/right-to-left-support-for-react-native-apps.html#writing-rtl-ready-components
MainActivity.java
#Override
protected String getMainComponentName() {
I18nUtil sharedI18nUtilInstance = I18nUtil.getInstance();
sharedI18nUtilInstance.allowRTL(context, true);
return "navapp";
}
AndroidManifest.xml
<application
android:name=".MainApplication"
android:label="#string/app_name"
android:icon="#mipmap/ic_launcher"
android:allowBackup="false"
android:theme="#style/AppTheme"
android:supportsRtl="true">
Arrows showing in your FlatList are coming from the ListItem component you are using to show every record in your data. You need to check for the current language/RTL support and render arrow accordingly.
To achieve desired behavior you can use rightIcon property for ListItem component.
rightIcon
icon configuration for right icon (optional), either a name from the
icon library (like material) or a React Native element like Image.
Shows up unless hideChevron is set
Sample
<ListItem
roundAvatar
title={'title'}
subtitle={'sub title'}
avatar={{uri: item.picture.thumbnail}}
containerStyle={{ borderBottomWidth: 0 }}
onPress={() => this.onLearnMore(item)}
rightIcon={{name: (I18nManager.isRTL ? 'chevron-left': 'chevron-right')}}
/>

Native-Base - CheckBox inside List not getting checked

I have imported CheckBox from NativeBase. On clicking the Checkbox, it calls the toggleCheckBox function to either add or remove the item.ids from the array and also set the flag to true or false based on the contents of the array.
I can see that the toggleCheckBox function works properly and it sets the array with item ids properly and the flag is also fine on click of the CheckBox. But, the checkbox inside the ListItem is not checked when the checkbox is clicked though the toggle function is called properly.
I also noticed that the log "MS CB2: " right above the List is printed after clicking the CheckBox but the log inside the List 'MS insideList :' is not printed. I am assuming that List is not rendered after the toggleCheckBox function is called.
Here is the code:
class MSScreen extends Component {
constructor(props){
super(props);
//this.toggleCheckbox = this.toggleCheckbox.bind(this);
this.state = {
isLoading: true,
checkboxes : [],
plans: {},
};
}
componentDidMount(){
console.log("MS inside componentDidMount");
fetch('http://hostname:port/getData')
.then((response) => {console.log('response'); return response.json();})
.then((responseJson) => {console.log('responseData: '+responseJson); this.setState({isLoading : false, plans : responseJson}); return;})
.catch((err) => {console.log(err)});
}
toggleCheckbox(id) {
let checkboxes = this.state.checkboxes;
if(checkboxes && checkboxes.includes(id)){
const index = checkboxes.indexOf(id);
checkboxes.splice(index, 1);
} else {
checkboxes = checkboxes.concat(id);
}
this.setState({checkboxes});
console.log("MS check a4: "+checkboxes && checkboxes.includes(id))
}
render() {
if (this.state.isLoading) {
return <View><Text>Loading...</Text></View>;
}
const plans = this.state.plans;
const { params } = this.props.navigation.state.params;
const checkboxes = this.state.checkboxes;
console.log("MS CB1: "+checkboxes)
return (
<Container>
<Content>
<View>
{console.log("MS CB2: "+checkboxes)}
<List
dataArray={plans.data}
renderRow={(item, i) => {
console.log('MS insideList : '+checkboxes && checkboxes.includes(item.id))
return(
<ListItem
key={item.id}
>
<Left>
<CheckBox
onPress={() => this.toggleCheckbox(item.id)}
checked={checkboxes && checkboxes.includes(item.id)}
/>
</Left>
<Text>
{item.name}
</Text>
</ListItem>)}}
/>
</View>
</Content>
</Container>
);
}
}
How do I get the CheckBox to get checked inside the List?
For the benefit of the other users, here is the code fix based on the suggestion from Supriya in the comments below:
SOLUTION
<FlatList
extraData={this.state}
data={plans.data}
keyExtractor={(item, index) => item.id}
renderItem={({item}) => {
const itemName = item.name;
return(
<ListItem>
<CheckBox
onPress={() => this.toggleCheckbox(item.id)}
checked={checkboxes && checkboxes.includes(item.id)}
/>
<Body>
<Text style={styles.planText}>
{item.name}
</Text>
</Body>
</ListItem>)}}
/>
Version:
native-base#2.3.5
react-native#0.50.4
Device: Android
CRNA app with Expo
There is a similar issue on github, https://github.com/GeekyAnts/NativeBase/issues/989 with solution
It works with straightforward code without listItem.
The following example handles the checkboxes as radio buttons, but the onPress functions can be changed easily to allow multiple selection.
import React, { Component } from 'react';
import { View } from 'react-native';
import { CheckBox, Text } from 'native-base';
export default class SignupScreen extends Component {
state = {
one: false,
two: false,
three: false
};
render() {
return (
<View style={{ alignItems: 'flex-start' }}>
<View style={{ flexDirection: 'row' }}>
<CheckBox checked={this.state.one}
style={{ marginRight: 20 }}
onPress={this.onePressed.bind(this)}/>
<Text>One</Text>
</View>
<View style={{ flexDirection: 'row' }}>
<CheckBox checked={this.state.two}
style={{ marginRight: 20 }}
onPress={this.twoPressed.bind(this)}/>
<Text>Two</Text>
</View>
<View style={{ flexDirection: 'row' }}>
<CheckBox checked={this.state.three}
style={{ marginRight: 20 }}
onPress={this.threePressed.bind(this)}/>
<Text>Three</Text>
</View>
</View>
);
}
// checkbox functions
// if clicked button was set, only clear it
// otherwise, set it and clear the others
onePressed() {
if (this.state.one)
this.setState({ one: false });
else
this.setState({ one: true, two: false, three: false });
}
twoPressed() {
if (this.state.two)
this.setState({ two: false });
else
this.setState({ one: false, two: true, three: false });
}
threePressed() {
if (this.state.three)
this.setState({ three: false });
else
this.setState({ one: false, two: false, three: true });
}
}

Categories

Resources