Add value of checkbox to an array when it is clicked - javascript

I have this situation where I want to transfer userid to an array which is defined in State.
I want to do it when I click on the checkbox to select it, and I want to remove the userid from the array when I deselect the checkbox
import React, { Component } from "react";
import {
View,
Text,
StyleSheet,
FlatList,
AsyncStorage
} from "react-native";
import axios from 'axios';
import { Button, Container, Content, Header, Body, Left, Right, Title } from 'native-base';
import Icon from 'react-native-vector-icons/Ionicons';
import { List, ListItem, SearchBar, CheckBox } from "react-native-elements";
// const itemId = this.props.navigation.getParam('itemId', 'NO-ID');
// const otherParam = this.props.navigation.getParam('otherParam', 'some default value');
class TeacherSubjectSingle extends Component{
static navigationOptions = {
header : null
}
// static navigationOptions = {
// headerStyle: {
// backgroundColor: '#8E44AD',
// },
// headerTintColor: '#fff',
// }
state = {
class_id: null,
userid: null,
usertype: null,
student_list: [],
faq : [],
checked: [],
}
componentWillMount = async () => {
const {class_id, student_list, userid, usertype} = this.props.navigation.state.params;
await this.setState({
class_id : class_id,
student_list : student_list,
userid : userid,
usertype : usertype,
})
console.log(this.state.class_id)
var result = student_list.filter(function( obj ) {
return obj.class_section_name == class_id;
});
this.setState({
student_list: result[0]
})
}
renderSeparator = () => {
return (
<View
style={{
height: 1,
width: "100%",
backgroundColor: "#CED0CE",
}}
/>
);
};
checkItem = (item) => {
const { checked } = this.state;
console.log(item)
if (!checked.includes(item)) {
this.setState({ checked: [...checked, item] });
} else {
this.setState({ checked: checked.filter(a => a !== item) });
}
console.log(checked)
};
render(){
return (
<Container>
<Header style={{ backgroundColor: "#8E44AD" }}>
<Left>
<Button transparent onPress={()=> this.props.navigation.navigate('ClassTeacher')}>
<Icon name="ios-arrow-dropleft" size={24} color='white' />
</Button>
</Left>
<Body>
<Title style={{ color: "white" }}>{this.state.class_id}</Title>
</Body>
<Right>
{this.state.checked.length !== 0 ? <Button transparent onPress={()=> this.props.navigation.navigate('ClassTeacher')}>
<Text>Start Chat</Text>
</Button> : null}
</Right>
</Header>
<View style={{flex: 1, backgroundColor: '#fff'}}>
<List containerStyle={{ borderTopWidth: 0, borderBottomWidth: 0 }}>
<FlatList
data={this.state.student_list.students}
extraData={this.state.checked}
renderItem={({ item }) => (
<ListItem
// roundAvatar
title={<CheckBox
title={item.name}
checkedColor='#8E44AD'
onPress={() => this.checkItem(item.userid)}
checked={this.state.checked.includes(item.userid)}
/>}
// subtitle={item.email}
// avatar={{ uri: item.picture.thumbnail }}
//containerStyle={{ borderBottomWidth: 0 }}
onPress={()=>this.props.navigation.navigate('IndividualChat', {
rc_id: item.userid,
userid: this.state.userid,
usertype: this.state.usertype,
subject_name: this.state.student_list.subject_name
})}
/>
)}
keyExtractor={item => item.userid}
ItemSeparatorComponent={this.renderSeparator}
/>
</List>
</View>
</Container>
);
}
}
export default TeacherSubjectSingle;
const styles = StyleSheet.create({
container:{
flex:1,
alignItems:'center',
justifyContent:'center'
}
});
this is the code for the same, I have created a function checkItem()for the same and it is working, the only problem is, when I click on the first item, it will output the blank array, I select the second item and it will return the array with first item and so on. Please help me resolve it, thanks in advance

Its because you are printing this.state.checked value just after the setState, setState is async, it will not immediately update the state value.
You can use setState callback method to check the updated state values.
Write it like this:
checkItem = (item) => {
const { checked } = this.state;
let newArr = [];
if (!checked.includes(item)) {
newArr = [...checked, item];
} else {
newArr = checked.filter(a => a !== item);
}
this.setState({ checked: newArr }, () => console.log('updated state', newArr))
};
Check this answer for more details about setState:
Why calling setState method doesn't mutate the state immediately?

Try below code:
checkItem = (e) => {
let alreadyOn = this.state.checked; //If already there in state
if (e.target.checked) {
alreadyOn.push(e.target.name); //push the checked value
} else {
//will remove if already checked
_.remove(alreadyOn, obj => {
return obj == e.target.name;
});
}
console.log(alreadyOn)
this.setState({checked: alreadyOn});
}

Like this, with an event listener and the .push method of an array.
var checkboxes = document.querySelectorAll('input[type=checkbox]');
var myArray = [];
for (var i = 0; i < checkboxes.length; i++) {
checkboxes[i].addEventListener("click", function(e) {
myArray.push(e.target.value);
console.log(myArray);
});
};
<div>
<input type="checkbox" name="feature" value="scales" />
<label >Scales</label>
</div>
<div>
<input type="checkbox" name="feature" value="horns" />
<label >Horns</label>
</div>
<div>
<input type="checkbox" name="feature" value="claws" />
<label >Claws</label>
</div>

Related

Why adding extra state helps to update other state?

Here is the full code:
import * as React from 'react';
import { View, ScrollView, StyleSheet } from 'react-native';
import {
Appbar,
Searchbar,
List,
BottomNavigation,
Text,
Button,
} from 'react-native-paper';
const AccordionCollection = ({ data }) => {
var bookLists = data.map(function (item) {
var items = [];
for (let i = 0; i < item.total; i++) {
items.push(
<Button mode="contained" style={{ margin: 10 }}>
{i}
</Button>
);
}
return (
<List.Accordion
title={item.title}
left={(props) => <List.Icon {...props} icon="alpha-g-circle" />}>
<View
style={{
flexDirection: 'row',
flexWrap: 'wrap',
alignItems: 'flex-start',
backgroundColor: 'white',
}}>
{items}
</View>
</List.Accordion>
);
});
return bookLists;
};
const MusicRoute = () => {
const DATA = [
{
key: 1,
title: 'Zain dishes',
total: 21,
},
{
key: 2,
title: 'Sides',
total: 32,
},
{
key: 3,
title: 'Drinks',
total: 53,
},
{
key: 4,
title: 'Aesserts',
total: 14,
},
];
const [data, setData] = React.useState(DATA);
const [searchQuery, setSearchQuery] = React.useState('');
const [sortAZ, setSortAZ] = React.useState(false);
const onChangeSearch = (query) => {
setSearchQuery(query);
const newData = DATA.filter((item) => {
return item.title.toLowerCase().includes(query.toLowerCase());
});
setData(newData);
};
const goSortAZ = () => {
setSortAZ(true);
setData(
data.sort((a, b) => (a.title > b.title ? 1 : b.title > a.title ? -1 : 0))
);
};
const goUnSort = () => {
setSortAZ(false);
setData(DATA);
};
return (
<View>
<Appbar.Header style={styles.appBar}>
<Appbar.BackAction onPress={() => null} />
<Searchbar
placeholder="Search"
onChangeText={onChangeSearch}
value={searchQuery}
style={styles.searchBar}
/>
<Appbar.Action
icon="sort-alphabetical-ascending"
onPress={() => goSortAZ()}
/>
<Appbar.Action icon="library-shelves" onPress={() => goUnSort()} />
</Appbar.Header>
<ScrollView>
<List.Section title="Accordions">
<AccordionCollection data={data} />
</List.Section>
</ScrollView>
</View>
);
};
const AlbumsRoute = () => <Text>Albums</Text>;
const MyComponent = () => {
const [index, setIndex] = React.useState(0);
const [routes] = React.useState([
{ key: 'music', title: 'Music', icon: 'queue-music' },
{ key: 'albums', title: 'Albums', icon: 'album' },
]);
const renderScene = BottomNavigation.SceneMap({
music: MusicRoute,
albums: AlbumsRoute,
});
return (
<BottomNavigation
navigationState={{ index, routes }}
onIndexChange={setIndex}
renderScene={renderScene}
/>
);
};
const styles = StyleSheet.create({
appBar: {
justifyContent: 'space-between',
},
searchBar: {
width: '60%',
shadowOpacity: 0,
borderRadius: 10,
backgroundColor: '#e4e3e3',
},
});
export default MyComponent;
Expo Snack Link
There are two weird mechanisms.
First
If I remove sortAZ(true) in goSortAZ() and sortAZ(false) in goUnSort(), the state data stops updating after you press on (1) sort and (2) unsort buttons more than three times.
Second
If I remove DATA array outside the component, sort and unsort buttons does not work/update.
If I do not remove these two, I can sort and unsort the list.
I feel that the code is messy although it achieves the function.
My questions is:
Why adding extra state (sortAZ) helps to update other state (data)?
Just totally remove sortAZ variable (no need to use it unless you somehow want to have a loading status, but since you are not making http requests, that's not necessary) and replace goSortAZ with the following:
Remember to clone the original array in order to create a new copy and then sort that copy.
This is working fine.
const goSortAZ = () => {
setData(
[...data].sort((a, b) => (a.title > b.title ? 1 : b.title > a.title ? -1 : 0))
);
};
i would suggest using the same technique for the unSort method too.

State of one checkbox affecting the others

I have this problem - I got multiple checkboxes as a part of my custom component (TimeButtonCheck) rendered on parent screen. On parent screen there is an array which is filled with - whether the checkboxes are checked or unchecked. But there is a problem happening. If I check/uncheck one of those checkboxes, all of them uncheck because they have same state in parent component. When I split the state into these child components I cant modify array of the parent component from child components. Can someone help me to solve this? Here is my code (child element):
const TimeButtonCheck = props => {
const [ceknute, setCeknute] = useState(true);
const [pole, setPole] = useState(["9:00", "10:00", "11:00"]);
const checkHandler = (id) => {
setCeknute(!ceknute);
if(!ceknute) {
const novePole = pole.slice();
novePole.push(id);
console.log("pushuj");
setPole(novePole);
console.log(novePole);
}
else
{
console.log("filtruj");
}
};
return (
<View style={styles.customButon}>
<CheckBox
checked = {ceknute}
key = {props.key}
onPress={(key) => {checkHandler(key)}}
checkedColor = {Colors.primaryColor}
containerStyle = {{padding:0,}}
/>
<TouchableOpacity activeOpacity={0.5}>
<Text
style={styles.textInButton}>
{props.cas}
</Text>
</TouchableOpacity>
</View>
);
And here is my parent component which is mapping those TimeButtonChecks on screen:
const JazdyInstruktor = props => {
const pole = ["8:00", "9:00", "10:00"];
const selectedStartDate = null;
const [isLoading, setIsLoading] = useState(true);
const [displayText, setDisplayText] = useState(true);
const dataToMap = ["11:00", "12:00", "13:00", "14:00", "15:00"];
const maper = (data) => {
return(
<View style = {{marginHorizontal: 18,}}>
<View style ={styles.instruktor}>
<InstruktorBar />
</View>
<View style = {styles.screen}>
{data.map((item) => {
return (
<TimeButtonCheck
key = {item}
cas={item}
/>
)})}
</View>
</View>
);
}
const startDate = selectedStartDate ? selectedStartDate.toString() : '';
const token = useSelector(state => state.auth.token);
return(
<View style={styles.container}>
<CalendarPicker
onDateChange={dateChangeHandler}
/>
<View>
{(isLoading) ? ((displayText) ? (<View style={styles.centered}><Text>Pre zobrazenie volnych terminov si vyberte datum</Text></View>) : (<View style = {{paddingTop: 10,
textAlign: 'center',}}><ActivityIndicator size='large' color={Colors.primaryColor}/></View>)) : **maper(dataToMap)**}
</View>
</View>
This is the case I can not modify parent array called pole through these child components - I can only modify separate arrays for every child component. Is there any way to solve this? Thank you.
Save the state in the parent component, the checkbox component only displays the data.
function CheckBox({ value, label, isChecked }) {
return (
<label>
<input type="checkbox" checked={isChecked} value={value} />
<span>{label}</span>
</label>
);
}
function Parent() {
// list of checkbox, `value` should be the format we want to save, label is something we want to display to the users
const list = [
{ value: "1100", label: "11:00" },
{ value: "1200", label: "12:00" },
{ value: "1300", label: "13:00" }
];
// every item default is un-checked
const [data, setData] = useState(() =>
list.map(item => ({
...item,
isChecked: false
}))
);
// update the check status in the parent component
function handleToggleCheckbox(value) {
setData(list =>
list.map(item => {
if (item.value === value) {
return {
...item,
isChecked: !item.isChecked
};
}
return item;
})
);
}
return (
<div className="App">
{data.map(({ value, label, isChecked }) => (
<CheckBox
key={value}
checked={isChecked}
value={value}
label={label}
onClick={() => handleToggleCheckbox(value)}
/>
))}
</div>
);
}
This is what happens when I console.log(data)
#

Pass function to semantic ui clearable prop

I have small portion of my app rendering a dropdown selection so users can view some brief information about library versions within the app.
The first dropdown is for the user to pick what they want view, for brevity I just added the relevant option for this question.
The second dropdown renders a fetched list of numbers pertaining to deviceIds. These deviceIds are fetched from a child class and then passed via props up to the parent class.
Now, In Semantic-UI-React, they have a dropdown module with a clearable prop which I am using on this dropdown populated with deviceIds. Below in VersionNumber class, you can see the props defined for the aforementioned dropdown.
The clearable prop lets the user remove the selected input from the dropdown. However, in my app when the input is removed it calls the onChange function which I do not want. I tried passing a custom change function to the clearable prop where I'm attempting to reset the state variable deviceId back to a undefined value if it's "cleared" by the user.
Is this possible? I'm pretty sure I'm taking the correct approach, but may be having an issue where the onChange function is firing before the clearable passed function.
I have a codesandbox that reproduces this problem here.
import React, { Component } from "react";
import ReactDOM from "react-dom";
import axios from "axios";
import {
Dropdown,
Form,
Divider,
Input,
Message,
Loader
} from "semantic-ui-react";
class App extends Component {
constructor(props) {
super(props);
this.state = {
viewSelection: "",
deviceId: "",
versionNum: "",
isLoading: true
};
}
handleViewSelection = (e, { value }) => {
this.setState({ viewSelection: value }, () => {
console.log("view election --> ", this.state.viewSelection);
});
};
onDeviceIdChange = async (e, { value }) => {
console.log("device id value -->", value);
this.setState({ deviceId: value }, () => {
console.log(
"deviceId value updated to state on select -->",
this.state.deviceId
);
});
try {
const { data } = await axios.get(`/deviceId/${value}`);
const version = data.data.versionNumber;
this.setState({ versionNum: version.version, isLoading: false }, () => {
console.log("callback from admin version fetch", this.state.versionNum);
});
} catch (error) {
console.error(Error(`Error getting the selected deviceId ${error.message}`));
}
};
handleClear = () => {
this.setState({ deviceId: "" }, () => {
console.log("handleClear function fired");
});
};
render() {
const { viewSelection, deviceId, versionNum, isLoading } = this.state;
return (
<div
style={{ display: "flex", minHeight: "100vh", flexDirection: "column" }}
>
<div style={{ flex: 1 }}>
<div
style={{
display: "flex",
flexDirection: "column",
justifyContent: "center",
alignItems: "center",
flex: "1"
}}
>
<div style={{ width: "1000px" }}>
<Divider style={{ marginTop: "7em" }} horizontal>
View Data
</Divider>
<Message style={{ marginTop: "2em" }} info>
<Message.Header>
Want to see more specific information? Log in
here.
</Message.Header>
</Message>
<Form.Field style={{ marginTop: "2em" }}>
<label>Select data to view</label>
<Dropdown
scrolling
placeholder="Pick an option"
value={viewSelection}
fluid
selection
multiple={false}
search
options={viewOptions}
onChange={this.handleViewSelection}
/>
</Form.Field>
{this.state.viewSelection && (
<div style={{ marginTop: "2em" }}>
{viewSelection && viewSelection === "versionNumber" ? (
<>
<VersionNumber
onDeviceIdChange={this.onDeviceIdChange}
deviceId={deviceId}
handleClear={this.handleClear}
/>
<div>
<label style={{ display: "block", marginTop: "2em" }}>
Version Number
</label>
{isLoading ? (
<Loader active inline="centered" />
) : (
<Input value={versionNum} fluid readOnly />
)}
</div>
</>
) : null}
</div>
)}
</div>
</div>
</div>
</div>
);
}
}
class VersionNumber extends Component {
constructor(props) {
super(props);
this.state = {
deviceId: "",
deviceIds: []
};
}
async componentDidMount() {
await this.getDeviceIds();
}
getDeviceIds = async () => {
try {
const { data } = await axios.get("/deviceIds");
console.log("device IDs --> ", data);
const deviceIds = data.data.deviceIds;
this.setState(
{
deviceIds: deviceIds
},
() => {
console.log(
"setState callback with updatesd deviceIds state -->",
this.state.deviceIds
);
}
);
} catch (error) {
console.error(Error(`Error getting deviceIds: ${error.message}`));
}
};
render() {
const { onDeviceIdChange, deviceId, handleClear } = this.props;
const { deviceIds } = this.state;
return (
<Form.Field required>
<label style={{ display: "block" }}>Device Id</label>
<Dropdown
id="deviceId"
value={deviceId}
onChange={onDeviceIdChange}
selection
fluid
placeholder="Please select an device id"
clearable={handleClear}
options={deviceIds.map(id => {
return {
text: id.id,
value: id.id,
key: id.id
};
})}
style={{ marginTop: ".33", marginBottom: "2em" }}
/>
</Form.Field>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
clearable prop expects a boolean value. You can change your onChange callback to consider the scenario where the value is going to be passed in as null / undefined
The function can be modified as below to reset the deviceId and prevent the API call
onDeviceIdChange = async (e, { value }) => {
// VALUE WILL BE PASSED IN AS "" WHEN THE CLEAR OPTION IS CLICKED
console.log("device id value -->", value);
this.setState({ deviceId: value }, () => {
console.log(
"deviceId value updated to state on select -->",
this.state.deviceId
);
});
// THIS IS THE CONDITION TO CATCH THE CLEARABLE INVOCATION
if(!value) {
this.handleClear();
return;
}
...
};
if(!value) return; Think of this condition as the execution that the clearable option will invoke. You can invoke anything before the return to ensure that your application handles the clear option in the way you expect it to.

How to close modal and return value from flatlist when click on item in react native?

I am creating country codes class. In which, I return list of country codes. I want to close modal that contains of list codes and also return the clicked item value of flat list that display list of modals.
I want return country code from modal screen to current js file. Here is my Codes modal Class:-
import React, { Component } from 'react';
import { StyleSheet, View,
Text,Modal,FlatList,TouchableWithoutFeedback} from 'react-native';
import { showMessage } from '../utils/GeneralFunctions';
import { Icon } from 'react-native-elements';
import TextInputBox from '../components/TextInputBox';
import {color} from '../values/color';
import {TextViewNonClickable} from '../components/TextView';
const countryCodes = require('../jsonData/codesCountry.json');
export default class Codes extends Component {
constructor(props) {
super(props);
this.state = {
countryCodes : countryCodes,
modalVisible : false,
searchedText : '',
loading : false,
selectedCountry : '',
};
this.arrayHolder = [];
}
componentWillMount = () => {
if(this.state.modalVisible == false){
this.setState({countryCodes : countryCodes})
}
this.arrayHolder = countryCodes;
};
//show countries modal
static showCountryModal = (modalVisibility) => {
showMessage("sunny");
if(modalVisibility == true){
this.setState({modalVisible:false})
}else{
this.setState({modalVisible:true})
}
}
//set Modal Visibility
static setModalVisibility(visibility){
showMessage("Set Modal Visibility : "+visibility);
this.setState({modalVisible:visibility});
}
//search country
searchText = (text) => {
const newData = this.arrayHolder.filter(item => {
const itemData = `${item.name.toUpperCase()}
${item.code.toUpperCase()} ${item.dial_code.toUpperCase()}`;
const textData = text.toUpperCase();
return itemData.indexOf(textData) > -1;
});
if(text != null){
this.setState({
countryCodes : newData,
});
}else if(text == " "){
this.setState({
countryCodes : countryCodes,
});
}
};
//setting selected country
selectedCountry = (item) => {
this.props.modalVisible = false;
this.setState({selectedCountry : item.dial_code})
showMessage("Code : " + item.dial_code)
}
_renderItem = ({item}) => {
return (
<TouchableWithoutFeedback onPress={() =>
this.selectedCountry(item)}>
<View style=
{{height:48,flexDirection:'row',
justifyContent:'center',alignItems:'center',
padding:16,borderBottomWidth:1,
borderBottomColor:color.pageBackground}}>
<TextViewNonClickable
textViewText={item.name+"("+item.code+")"}
textStyle=
{{fontSize:16,fontWeight:'bold',flex:0.85,
color:color.colorBlack}}
/>
<TextViewNonClickable
textViewText={item.dial_code}
textStyle=
{{fontSize:16,fontWeight:'bold',flex:0.15,
color:color.colorBlack}}
/>
</View>
</TouchableWithoutFeedback>
)
}
render() {
// const {modalVisible} = this.props;
return (
<Modal
animationType='slide'
transparent={false}
visible={this.state.modalVisible}
onRequestClose={() => this.setState({
countryCodes : countryCodes})}
>
<View>
<View style={{flexDirection:'row',height:48,
justifyContent:"center",alignItems:'center',
borderBottomWidth:1,paddingStart:16,paddingRight:16}}>
<Icon
name='search' type='material-icons'
size={24} color='black'
/>
<TextInputBox
textInputStyle=
{{borderColor:color.colorTransparent,
color:color.colorHintText,flex:1}}
placeHolderText='Search here...'
onChangeText={text =>
this.searchText(text)}
/>
</View>
<View>
<FlatList
data={this.state.countryCodes}
renderItem={this._renderItem}
keyExtractor={(item,index) =>
item+index}
showsVerticalScrollIndicator={false}
/>
</View>
</View>
</Modal>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
});
Here is my codesClass.js class
import React, { Component } from 'react';
import {StyleSheet,View,ImageBackground} from 'react-native';
import { HeaderView } from '../components/Headers';
import { Actions } from 'react-native-router-flux';
import { appString } from '../values/appStrings';
import { color } from '../values/color';
import TextInputBox from '../components/TextInputBox';
import TextViewClickable from '../components/TextView';
import Button from '../components/Buttons';
import {showToast, showMessage} from '../utils/GeneralFunctions'
import { dimension } from '../values/dimensions';
import Codes from '../dialogs/Codes';
export default class SignUpScreen extends Component {
constructor(props) {
super(props);
this.state = {
countryCode : '',
phone : '',
modalVisible:false,
};
}
openOrCloseCountryCodes = () => {
if(this.state.modalVisible == false){
// this.setState({modalVisible:true});
Codes.setModalVisibility(true);
}else{
// this.setState({modalVisible:false});
Codes.setModalVisibility(false);
}
// Codes.showCountryModal(true);
}
render() {
return (
<View>
<View style={{flexDirection:'row',marginTop:20}}>
<TextViewClickable
textViewText={this.state.countryCode != '' ?
this.state.countryCode : '+91'}
touchableButtonStyle={styles.touchableButtonStyle}
textStyle={styles.textStyle}
onPress={() =>
{this.openOrCloseCountryCodes();}}
/>
<TextInputBox
placeHolderText={appString.placeholderPhoneNumber}
onChangeTextSet={(text) => {this.setState({
phone : text})}}
textInputStyle={{flex : 1,marginLeft : 4}}
/>
</View>
<Codes modalVisible={this.state.modalVisible}
closeModal={() => this.openOrCloseCountryCodes()}/>
</View>
);
}
}
const styles = StyleSheet.create({
parentView : {
flex: 1,
alignItems: 'center',
},
touchableButtonStyle: {
marginRight : 4,
borderRadius: dimension.textInputBorderRadius,
borderWidth: dimension.textInputBorderWidth,
borderColor: color.textInputBorderColor,
justifyContent : 'center',
alignItems:'center',
paddingLeft: 16,
paddingRight: 16,
},
textStyle : {
fontSize: dimension.regularFontSize,
color : color.colorHintText,
}
});
onRequestClose on Modal should be:
onRequestClose={() => this.props.closeModal(this.state.selectedCountry)}
and SignUpScreen, handle callback value:
<Codes
modalVisible={this.state.modalVisible}
closeModal={(selectedCountry) => {
this.openOrCloseCountryCodes()
// do something with selectedCountry
console.log(selectedCountry)
}}
/>
In your case I assume the closing and opening of Modal is working.
In the below function you set the selected country code to a certain state along with it close the modal and pass the value to class Codes create another function same as showCountryModal and set it to a state there.
In class signUpScreen paste the below changes
Code below :
selectedCountry = (item) => {
this.openOrCloseCountryCodes();
Codes. setSelectedCountryCode(item.dial_code);
this.setState({selectedCountry : item.dial_code})
showMessage("Code : " + item.dial_code)
}
In class Codes paste the below changes
Code below :
// initialise `state` `countryCode`
constructor(props) {
super(props);
this.state = {
countryCodes : countryCodes,
modalVisible : false,
searchedText : '',
loading : false,
selectedCountry : '',
countryCode: ""
};
this.arrayHolder = [];
}
//set selected country
static setSelectedCountryCode = (countryCode) => {
this.setState({countryCode: countryCode})
}
Also include onRequestClose so that backbuttonclick of android gets handled
on onRequestClose call the function to close the modal
You should study the concept of props and the static method idea not that great to control modal visibility use props instead.

React Native Elements Checkbox Should be checked after clicking

I'm using React Native Elements CheckBox inside List Items, of Flat List.
import React, { Component } from "react";
import { View, Text, StyleSheet, FlatList } from "react-native";
import axios from "axios";
import {
Button,
Container,
Content,
Header,
Body,
Left,
Right,
Title
} from "native-base";
import Icon from "react-native-vector-icons/Ionicons";
import { List, ListItem, SearchBar, CheckBox } from "react-native-elements";
// const itemId = this.props.navigation.getParam('itemId', 'NO-ID');
// const otherParam = this.props.navigation.getParam('otherParam', 'some default value');
class TeacherSubjectSingle extends Component {
static navigationOptions = {
header: null
};
// static navigationOptions = {
// headerStyle: {
// backgroundColor: '#8E44AD',
// },
// headerTintColor: '#fff',
// }
state = {
class_id: null,
userid: null,
usertype: null,
student_list: [],
faq: [],
checked: []
};
componentWillMount = async () => {
const {
class_id,
student_list,
userid,
usertype
} = this.props.navigation.state.params;
await this.setState({
class_id: class_id,
student_list: student_list,
userid: userid,
usertype: usertype
});
console.log(this.state.class_id);
var result = student_list.filter(function(obj) {
return obj.class_section_name == class_id;
});
this.setState({
student_list: result[0]
});
};
renderSeparator = () => {
return (
<View
style={{
height: 1,
width: "100%",
backgroundColor: "#CED0CE"
}}
/>
);
};
checkItem = item => {
const { checked } = this.state;
if (!checked.includes(item)) {
this.setState({ checked: [...checked, item] });
} else {
this.setState({ checked: checked.filter(a => a !== item) });
}
};
render() {
return (
<Container>
<Header style={{ backgroundColor: "#8E44AD" }}>
<Left>
<Button
transparent
onPress={() => this.props.navigation.navigate("ClassTeacher")}
>
<Icon name="ios-arrow-dropleft" size={24} color="white" />
</Button>
</Left>
<Body>
<Title style={{ color: "white" }}>{this.state.class_id}</Title>
</Body>
<Right />
</Header>
<View style={{ flex: 1, backgroundColor: "#fff" }}>
<List containerStyle={{ borderTopWidth: 0, borderBottomWidth: 0 }}>
<FlatList
data={this.state.student_list.students}
renderItem={({ item }) => (
<ListItem
// roundAvatar
title={
<CheckBox
title={item.name}
onPress={() => this.checkItem(item.userid)}
checked={this.state.checked.includes(item.userid)}
/>
}
// subtitle={item.email}
// avatar={{ uri: item.picture.thumbnail }}
containerStyle={{ borderBottomWidth: 0 }}
onPress={() =>
this.props.navigation.navigate("IndividualChat", {
rc_id: item.userid,
userid: this.state.userid,
usertype: this.state.usertype,
subject_name: this.state.student_list.subject_name
})
}
/>
)}
keyExtractor={item => item.userid}
ItemSeparatorComponent={this.renderSeparator}
/>
</List>
</View>
</Container>
);
}
}
export default TeacherSubjectSingle;
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: "center",
justifyContent: "center"
}
});
Above is my code for the same, I have tried every possibility and checked the GitHub page for the same, but my items are not getting checked if I press on the checkbox.
My renderItem will have an array to render which is having a field like 'name' and 'userid'.
This is the example of the code from where I have coppied the coding for the same, where it is working
I want to save selected ids to an array so that I can pass that as a prop to the next screen.
Since FlatList is a PureComponent, it will not re-render the items unless the data changes. If you want the FlatList to re-render when checked array changes, you need to pass it to e.g. extraData.
<FlatList
data={this.state.student_list.students}
extraData={this.state.checked}
renderItem={({ item }) => {
// ...
}}
keyExtractor={item => item.userid}
ItemSeparatorComponent={this.renderSeparator}
/>

Categories

Resources