React Native Elements Checkbox Should be checked after clicking - javascript

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}
/>

Related

delete list element using filter method

I am working on todo list in native , i have a function called onDelete but when i click on it , it delete all element in list and after then program crashed.
this is my main file where i have stored value as key , value pair
export default function App() {
const [courseGoal, setCourseGoal] = useState([]);
const [count, setCount] = useState('');
const submitHandler = () => {
setCourseGoal((currGoal) => [
...currGoal,
{ key: Math.random().toString(), value: count },
]);
};
console.log('App', courseGoal)
return (
<View style={styles.container}>
<SearchBar
setCourseGoal={setCourseGoal}
count={count}
setCount={setCount}
submitHandler={submitHandler}
/>
<ListItem courseGoal={courseGoal} setCourseGoal={setCourseGoal} courseGoal={courseGoal}/>
</View>
);
}
this is my list component where i am facing issue, you can see ondelete here.
import React from "react";
import { StyleSheet, Text, TouchableOpacity } from "react-native";
import { FlatList } from "react-native-web";
export default function ListItem(props) {
const onDelete = (goalId) => {
props.setCourseGoal((currGoal) => {
currGoal.filter((goal) => goal.key !== goalId);
console.log("clicked", props.courseGoal[0].key);
});
};
return (
<FlatList
data={props.courseGoal}
keyExtractor={(item, index) => item.key}
renderItem={(itemData) => (
<TouchableOpacity
onPress={onDelete.bind(itemData.item.key)}
activeOpacity={0.2}
>
<Text style={styles.listData}>{itemData.item.value}</Text>
{console.log(itemData.item.key)}
</TouchableOpacity>
)}
/>
);
}
this is my main component where i have my search input
import React from "react";
import { View, Text, StyleSheet, Pressable, TextInput } from "react-native";
export default function SearchBar(props) {
const onInputHandler = (value) => {
props.setCount(value);
};
return (
<View style={styles.searchBox}>
<Pressable style={styles.submitBtn} title="Click Me !">
<Text>☀️</Text>
</Pressable>
<TextInput
style={styles.searchInput}
placeholder="Enter Goal"
onChangeText={onInputHandler}
/>
<Pressable
style={styles.submitBtn}
title="Click Me !"
onPress={props.submitHandler}
>
<Text>🔥🔥</Text>
</Pressable>
</View>
);
}
const styles = StyleSheet.create({
searchBox: {
flexDirection: "row",
justifyContent: "space-around",
},
searchInput: {
width: "90%",
textAlign: "center",
padding: 10,
// color: 'white',
borderRadius: 10,
borderWidth: 1,
marginHorizontal: 5,
},
submitBtn: {
color: "black",
justifyContent: "space-around",
padding: 10,
borderRadius: 10,
borderWidth: 1,
},
});
You have to return the filtered array from your onDelete function
const onDelete = (goalId) => {
props.setCourseGoal((currGoal) => {
return currGoal.filter((goal) => goal.key !== goalId);
});
};

render data in FlatList React Native (expo cli) from firebase realtime database?

I'm working on a ToDo app that is connected to the Firebase real-time database. Everything works fine. I can also store data in the Firebase database, but the problem is that I cannot get any data from the database. I want to render data in ScrollView so that the data can be displayed in ScrollView when I open my app.
I'm getting error: ReferenceError: noteArray is not defined <FlatList data={noteArray}
I have uploaded my whole code [codesandbox.io/s/stupefied-snowflake-1lddp?file=/src/App.js][1]
Main.js
import React, { Component } from "react";
import {
StyleSheet,
Text,
View,
TextInput,
TouchableOpacity,
FlatList
} from "react-native";
import Note from "./note";
import firebase from "./firebase";
export default class Main extends React.Component {
constructor(props) {
super(props);
this.state = {
noteArray: [],
noteText: ""
};
}
componentDidMount() {
this.listenForNotes();
}
listenForNotes() {
firebase
.database()
.ref(`todos`)
.on("value", function (snapshot) {
const notes = [];
snapshot.forEach((child) => {
notes.push({
note: child.val().name,
date: child.val().date,
key: child.key
});
});
this.setState({
noteArray: notes
});
});
}
adTask() {
if (this.state.noteText) {
var date = new Date();
var database = firebase.database().ref("todos");
var key = database.push().key;
var todo = {
date:
date.getDay() +
"/" +
(date.getMonth() + 1) +
"/" +
date.getFullYear(),
note: this.state.noteText,
key: key
};
database.child(key).set(todo);
this.setState({ noteText: "" });
}
}
deleteNote(key) {
// your delete note function
}
render() {
return (
<View style={styles.container}>
<View style={styles.header}>
<Text style={styles.headerText}>Todo</Text>
</View>
<FlatList
data={this.state.noteArray}
renderItem={({ item, index }) => {
return (
<Note
key={item.key}
note={item.note}
date={item.date}
deleteMethod={() => this.deleteNote(item.key)}
/>
);
}}
key={(item) => `${item.key}`}
/>
<View style={styles.footer}>
<TextInput
style={styles.textInput}
onChangeText={(noteText) => this.setState({ noteText })}
value={this.state.noteText}
placeholder="Enter Task"
placeholderTextColor="white"
underlineColorAndroid="transparent"
></TextInput>
</View>
<TouchableOpacity
onPress={this.adTask.bind(this)}
style={styles.addButton}
>
<Text style={styles.addButtonText}>Add</Text>
</TouchableOpacity>
</View>
);
}
}
note.js
import React from "react";
import { StyleSheet, Text, View, TouchableOpacity } from "react-native";
export default class Note extends React.Component {
constructor(props) {
super(props);
}
render() {
const { note, date, key, deleteMethod } = this.props;
return (
<View key={key} style={styles.note}>
<Text style={styles.noteText}>{note}</Text>
<Text style={styles.noteDate}>{date}</Text>
<TouchableOpacity onPress={deleteMethod} style={styles.noteDelete}>
<Text style={styles.noteDeleteText}>
<AntDesign name="delete" size={24} color="black" />
</Text>
</TouchableOpacity>
</View>
);
}
}
const styles = StyleSheet.create({
note: {
position: "relative",
padding: 20,
paddingRight: 100,
borderBottomWidth: 2,
borderBottomColor: "#ededed"
},
noteText: {
fontWeight: "bold",
fontSize: 18,
paddingLeft: 20,
borderLeftWidth: 10,
borderLeftColor: "#e91e63"
},
noteDate: {
paddingLeft: 20,
borderLeftWidth: 10,
borderLeftColor: "#e91e63"
},
noteDelete: {
position: "absolute",
justifyContent: "center",
alignItems: "center",
backgroundColor: "#2980b9",
padding: 10,
top: 10,
bottom: 10,
right: 10
},
noteDeleteText: {
color: "white"
}
});
[1]: http://codesandbox.io/s/stupefied-snowflake-1lddp?file=/src/App.js
it should be this.state.noteArray since noteArray is a state variable.
there are couple of errors in the code sandbox
<FlatList
data={noteArray}
renderItem={({ item, index }) => {
should be
<FlatList
data={this.state.noteArray}
renderItem={({ item, index }) => {
and key, should be item.key:
deleteMethod={() => this.deleteNote(key)}
should be
deleteMethod={() => this.deleteNote(item.key)}
this.setState doesn't exist is because you have a function instead of an array function. change it to the following should work:
.on("value", snapshot => {
const notes = [];
snapshot.forEach((child) => {
notes.push({
note: child.val().name,
date: child.val().date,
key: child.key
});
});
this.setState({noteArray: notes});
});

New to react native, Buttons don't seem to work individually

I'm trying to get each button to activate and "switch-on" when pressed, and I've used some documentation to help me. However, now it is not switching on.
Code Adds Switches in a FlatList
The Data should look like this:
https://imgur.com/a/761PSjre
Also, feel free to judge my code to the darkest depths of hell. I'm trying to improve my code.
import React from 'react'
import {StyleSheet, View,Text, Switch, Button, Alert, ScrollView, FlatList, SafeAreaView} from 'react-native'
export default () => {
const DATA = [
{
index: 1,
title: 'Toggle Night Mode',
},
{
index: 2,
title: 'Remind me to take a break',
},
{
index: 3,
title: "Remind me when it's bedtime",
},
];
const [enabledSwitches, setEnabledSwitches] = React.useState(DATA.length);
const toggleSwitch = () => setEnabledSwitches(previousState => !previousState);
function Item({title, index}) {
return (
<View>
<Text style={styles.text}> {title} </Text>
<Switch
trackColor={{ false: "#767577", true: "#81b0ff" }}
thumbColor="#f5dd4b"
ios_backgroundColor="#3e3e3e"
value={enabledSwitches[index]}
onValueChange={() => toggleSwitch(switches => {
switches[index] = !switches[index];
return switches;
})}
/>
</View>
)
}
function Header(){
return(
<View style = {styles.header}>
<Text style={styles.headertext}>Settings</Text>
</View>
)
}
return (
<>
<View style = {styles.container}>
<FlatList
data = {DATA}
keyExtractor = {item => item.id}
renderItem = {({ item, index }) => <Item title={item.title} index={index} /> }
ListHeaderComponent = {Header()}
/>
</View>
<View>
<Button
title = "Clear Search History"
color = "#6fb6f0"
onPress = {() => Alert.alert('Food History Has Been Cleared!')}
/>
</View>
<View>
<Button
title = "Logout"
color = "#6fb6f0"
onPress = {() => Alert.alert('Successfully Logged Out!')}
/>
</View>
</>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
text: {
fontSize: 20,
fontWeight: "300"
},
headertext: {
fontSize: 30,
fontWeight: "300"
},
header:{
flex:1,
justifyContent: 'center',
alignItems: 'center',
padding: 10,
backgroundColor: '#f5f5f5'
}
})
Try this way
import React from 'react'
import {StyleSheet, View,Text, Switch, Button, Alert, ScrollView, FlatList, SafeAreaView} from 'react-native'
export default () => {
// use data set in default state
const [data, setData] = React.useState([ {index: 1,title: 'Toggle Night Mode'},...]);
function toggleSwitch(value, index){
const newData = [...data];
const newData[index].isEnable = value;
setData(newData);
}
function Item({item, index}) {
return (
<View>
<Text style={styles.text}> {item.title} </Text> // use `title` here like this
<Switch
.....
value={item.isEnable || false} // change here
onValueChange={(value) => toggleSwitch(value, index) } // change here
/>
</View>
)
}
return (
<>
<View style = {styles.container}>
<FlatList
data = {data}
keyExtractor = {item => item.id}
renderItem = {({ item, index }) => <Item item={item} index={index} /> } // send `item` as prop
/>
</View>
</>
);
}

Flatlist does not render if have one object in data?

I have some issue with Flatlist, I have an array of objects I got them from DB,
and save them to state, now when I log the this.state.providers in render() method or in the callback func after setState I got the valid Object like this
[{username: "Test", key: "53HoDga6aYhHsV5pCi5sx6LGbx42"}]
but when I passed these object into data prop in <Flatlist data={this.state.providers} /> the flatlist not rendering!
but when I add the object in the data prop manual like this
<Flatlist data={[{username: "Test One", key: "53HoDga6aYhHsV5pCi5sx6LGbx42"}]}
the flatlist work very well,
But I'm sure the code is correct because I added them into other project and work very well!!
Edit
when I pass tow object into the array the flatlist work!!
so how to handle it if I got one object from DB!
Code
import React, { Component } from "react";
import firebase from "react-native-firebase";
import Icon from "react-native-vector-icons/Ionicons";
import {
View,
Text,
StyleSheet,
FlatList,
TouchableOpacity,
Dimensions
} from "react-native";
class ListChats extends Component {
constructor(props) {
super(props);
this.state = {
providers: []
};
}
_chatList = () => {
let currentUser = firebase.auth().currentUser.uid;
let ref = firebase.database().ref(`Messages/${currentUser}`);
let providersKeys = [];
ref.once("value").then(snapshot => {
snapshot.forEach(childsnap => {
console.log(childsnap.key);
providersKeys.push(childsnap.key);
});
let usernames = [];
providersKeys.forEach(key => {
firebase
.database()
.ref("users")
.child(key)
.once("value")
.then(providersShot => {
let username = providersShot.val().username;
usernames.push({ username: username, key: key });
});
});
this.setState({ providers: usernames }, () =>
console.log(this.state.providers)
);
});
};
componentDidMount() {
this._chatList();
}
_listEmptyComponent = () => {
return (
<View style={styles.container}>
<Text style={{ alignSelf: "center" }}>No Chats Found :O</Text>
</View>
);
};
render() {
console.log(this.state.providers); // I got [{username: "Test", key: "53HoDga6aYhHsV5pCi5sx6LGbx42"}]
return (
<View style={{ flex: 1 }}>
<FlatList
key={Math.random() * 1000}
data={this.state.providers}
contentContainerStyle={{ flexGrow: 1 }}
ListEmptyComponent={this._listEmptyComponent()}
keyExtractor={item => item.key.toString()}
renderItem={({ item }) => {
console.log("item", item);
return (
<TouchableOpacity
onPress={() =>
this.props.navigation.navigate("ChatDetails", {
Key: item.key,
providerName: item.username
})
}
>
<View style={styles.parent}>
<Icon name="ios-contact" size={50} color="#4d8dd6" />
<View
style={{
flex: 1,
justifyContent: "flex-start",
alignItems: "flex-start",
marginHorizontal: 25
}}
>
<Text
style={{
color: "#000",
fontSize: 17
}}
>
{item.username}
</Text>
</View>
<Icon name="ios-chatboxes" size={25} color="#d6d6d6" />
</View>
</TouchableOpacity>
);
}}
// keyExtractor={(item, index) => index.toString()}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1
},
parent: {
flexDirection: "row",
justifyContent: "space-between",
alignItems: "center",
paddingVertical: 25,
marginHorizontal: 15,
borderBottomWidth: 1,
borderBottomColor: "#eee"
}
});
export default ListChats;
You should add extraData property to FlatList:
extraData={this.state}
In here your using usernames.push method to add the data objects to array, using this method will not indicate the state about a need of a re-render even if the state is updated with a new array.
For this usual coding pattern is using the spread operator
this.setState({ providers: [...usernames] })
Use "extraData" props of FlatList.

Add value of checkbox to an array when it is clicked

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>

Categories

Resources