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);
Related
So I have tried to implement this code from user illusionist from another issue concerning auto filling text input with suggested text here in react native LINK: How to get suggestions while typing in text-input in react-native
this is how I implemented it >
import { Menu, TextInput } from "react-native-paper";
import React, { useState } from "react";
const Autocomplete = ({
value: origValue,
label,
data,
containerStyle,
onChange: origOnChange,
icon = 'bike',
style = {},
menuStyle = {},
right = () => {},
left = () => {},
}) => {
const [value, setValue] = useState(origValue);
const [menuVisible, setMenuVisible] = useState(false);
const [filteredData, setFilteredData] = useState([]);
const filterData = (text) => {
return data.filter(
(val) => val?.toLowerCase()?.indexOf(text?.toLowerCase()) > -1
);
};
return (
<View style={[containerStyle]}>
<TextInput
onFocus={() => {
if (value.length === 0) {
setMenuVisible(true);
}
}}
// onBlur={() => setMenuVisible(false)}
label={label}
right={right}
left={left}
style={style}
onChangeText={(text) => {
origOnChange(text);
if (text && text.length > 0) {
setFilteredData(filterData(text));
} else if (text && text.length === 0) {
setFilteredData(data);
}
setMenuVisible(true);
setValue(text);
}}
value={value}
/>
{menuVisible && filteredData && (
<View
style={{
flex: 1,
backgroundColor: 'white',
borderWidth: 2,
flexDirection: 'column',
borderColor: 'grey',
}}
>
{filteredData.map((datum, i) => (
<Menu.Item
key={i}
style={[{ width: '100%' }, menuStyle]}
icon={icon}
onPress={() => {
console.log(datum)
setValue(datum);
console.log(value)
setMenuVisible(false);
}}
title={datum}
/>
))}
</View>
)}
</View>
);
};
export default Autocomplete;
and in another page I import autocomplete and like here:
const [typZavady, setTypZavady] = useState('');
<Autocomplete
value={''}
style={[novaStyle.input]}
containerStyle={novaStyle.autocompleteContainer}
label="Typ závady"
data={['Svetla', 'Stoličky', 'Tabula', 'Projektor', 'Topenie', 'Počítače', 'Dvere', 'Iné']}
menuStyle={{backgroundColor: 'white'}}
onChange={newTyp => setTypZavady(newTyp)}
/>
However when I type and click on one of the suggested words only the part of the word I type in is stored in the const typZavady not the selected suggested word. I fiddled a bit with the code with no luck.
I am learning React Native and i am trying to display some dynamic data using for loop and arrow function.
I am facing issues exactly data is not showing on screen but inside log it is printing for loop data.
What is wrong in this code ? As i am only able to see 49 as a value in console.warn.
Code
import React, { Component } from 'react';
import { StyleSheet, View, Text, ScrollView, Platform, Alert } from 'react-native';
export default class MyApp extends Component {
constructor() {
super();
}
dynamicList = () => {
var myloop = [];
for (let i = 0; i < 50; i++) {
console.warn(i)
myloop.push(
<View key={i} style={styles.item}>
<Text style={styles.item_text_style} onPress={() => { Alert.alert('Alert', `Title ${i.toString()}`) }}>Title {i}</Text>
<View style={styles.item_separator} />
</View>
);
}
}
render() {
return (
<ScrollView>
<View >
<Text >Welcome to React Native!</Text>
{this.dynamicList()}
</View>
</ScrollView>
);
}
}
const styles = StyleSheet.create(
{
MainContainer:
{
flex: 1,
paddingTop: 25
},
item_text_style:
{
fontSize: 20,
color: '#000',
padding: 10
},
item_separator:
{
height: 1,
width: '100%',
backgroundColor: '#263238',
}
});
wrap your function in componentDidMount() above render, like
componentDidMount(){
this.dynamicList()
}
Also, you are pushing your items in an array, so should use javasSript map method to display the key value pairs from an array
Please update your dynamicList function to following
dynamicList = () => {
var myloop = [];
for (let i = 0; i < 50; i++) {
console.warn(i)
myloop.push(
<View key={i} style={styles.item}>
<Text style={styles.item_text_style} onPress={() => { Alert.alert('Alert', `Title ${i.toString()}`) }}>Title {i}</Text>
<View style={styles.item_separator} />
</View>
);
}
return myloop;
}
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>
);
}
}
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')}}
/>
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 });
}
}