render only 10 item in react native flatlist on each page, then the next 5 on pull to load more item - javascript

i want to do paging but i cant limit the item to 10. this code shows all the items.
these are not working as well -initialNumToRender,maxToRenderPerBatch,windowSize
<FlatList
data={DATA}
renderItem={({ item }) => (
<Item title={item.name} />
)}
keyExtractor={item => item.id}
ItemSeparatorComponent={ItemSeparatorView}
initialNumToRender={11}
maxToRenderPerBatch={5}
windowSize={2}
/>

Try this,
import React, {useState, useEffect} from 'react';
//import all the components we are going to use
import {
SafeAreaView,
View,
Text,
TouchableOpacity,
StyleSheet,
FlatList,
ActivityIndicator,
} from 'react-native';
const App = () => {
const [loading, setLoading] = useState(true);
const [dataSource, setDataSource] = useState([]);
const [offset, setOffset] = useState(1);
useEffect(() => getData(), []);
const getData = () => {
console.log('getData');
setLoading(true);
//Service to get the data from the server to render
fetch('https://aboutreact.herokuapp.com/getpost.php?offset='
+ offset)
//Sending the currect offset with get request
.then((response) => response.json())
.then((responseJson) => {
//Successful response
setOffset(offset + 1);
//Increasing the offset for the next API call
setDataSource([...dataSource, ...responseJson.results]);
setLoading(false);
})
.catch((error) => {
console.error(error);
});
};
const renderFooter = () => {
return (
//Footer View with Load More button
<View style={styles.footer}>
<TouchableOpacity
activeOpacity={0.9}
onPress={getData}
//On Click of button load more data
style={styles.loadMoreBtn}>
<Text style={styles.btnText}>Load More</Text>
{loading ? (
<ActivityIndicator
color="white"
style={{marginLeft: 8}} />
) : null}
</TouchableOpacity>
</View>
);
};
const ItemView = ({item}) => {
return (
// Flat List Item
<Text
style={styles.itemStyle}
onPress={() => getItem(item)}>
{item.id}
{'.'}
{item.title.toUpperCase()}
</Text>
);
};
const ItemSeparatorView = () => {
return (
// Flat List Item Separator
<View
style={{
height: 0.5,
width: '100%',
backgroundColor: '#C8C8C8',
}}
/>
);
};
const getItem = (item) => {
//Function for click on an item
alert('Id : ' + item.id + ' Title : ' + item.title);
};
return (
<SafeAreaView style={{flex: 1}}>
<View style={styles.container}>
<FlatList
data={dataSource}
keyExtractor={(item, index) => index.toString()}
ItemSeparatorComponent={ItemSeparatorView}
enableEmptySections={true}
renderItem={ItemView}
ListFooterComponent={renderFooter}
/>
</View>
</SafeAreaView>
);
};
const styles = StyleSheet.create({
container: {
justifyContent: 'center',
flex: 1,
},
footer: {
padding: 10,
justifyContent: 'center',
alignItems: 'center',
flexDirection: 'row',
},
loadMoreBtn: {
padding: 10,
backgroundColor: '#800000',
borderRadius: 4,
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
},
btnText: {
color: 'white',
fontSize: 15,
textAlign: 'center',
},
});
export default App;

Related

How to display products in Flatlist properly?

I am trying to display some fetched products in a FlatList, also to display more products when I reach the end of this FlatList, but I am getting this error: Invariant Violation: ScrollView child layout (["alignItems"]) must be applied through the contentContainerStyle prop.
When I change alignItems from style to contentContainerStyle the app closes without showing an error or alert.
If I remove the alignItems from container the app closes too
export default function NewProducts() {
const [products, setProducts] = useState([]);
const [isLoading, setisLoading] = useState(false);
const [startLimit, setStartLimit] = useState({ start: 0, limit: 10 });
const navigation = useNavigation();
useEffect(() => {
setisLoading(true);
getProducts();
}, [startLimit]);
const gotoProduct = (id) => {
navigation.push("product", { idProduct: id });
};
const getProducts = async () => {
const response = await getLastProductsApi(
startLimit.start,
startLimit.limit
);
console.log(response);
setProducts(response);
};
const renderItem = ({product}) => {
return (
<TouchableWithoutFeedback
key={product.id}
onPress={() => gotoProduct(product.id)}
>
<View style={styles.containerProduct}>
<View style={styles.product}>
<Image
style={styles.image}
source={{
uri: `${product.attributes.images.data[0].attributes.formats.small.url}`,
}}
/>
<Text style={styles.name} numberOfLines={1} ellipsizeMode="tail">
{product.attributes.title}
</Text>
</View>
</View>
</TouchableWithoutFeedback>
);
};
const renderFooter = () => {
return isLoading && <Loading text="Loading more products" size="medium" />;
};
const handleLoadMore = () => {
setStartLimit({
start: startLimit.start + 10,
limit: startLimit.limit + 10,
});
setisLoading(true);
};
return (
<FlatList
style={styles.container}
numColumns={2}
data={products}
renderItem={renderItem}
keyExtractor={(item, index) => index.toString()}
ListFooterComponent={renderFooter}
onEndReached={handleLoadMore}
onEndReachedThreshold={0}
/>
);
}
const styles = StyleSheet.create({
container: {
alignItems: "flex-start",
marginTop: 1,
},
containerProduct: {
padding: 3,
},
product: {
padding: 10,
backgroundColor: "#f0f0f0",
borderRadius: 20,
},
image: {
height: 150,
resizeMode: "contain",
borderRadius: 20,
},
name: {
marginTop: 15,
fontSize: 15,
},
});
Here is where I call this component
export default function Home() {
return (
<>
<StatusBarCustom
backgroundColor={colors.primary}
barStyle="light-content"
/>
<Search />
<View>
<Banner />
<NewProducts />
</View>
</>
);
}
When you use renderItem from FlatList you have to use item and not product: https://reactnative.dev/docs/flatlist#required-renderitem
You can replace
const renderItem = ({product}) => {
By
const renderItem = ({item}) => {

Check the render method of `RestApi`

i got this This error
Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
Check the render method of RestApi.
This is my code App.js
import React from 'react';
import { StyleSheet } from 'react-native';
import RestApi from './x/RestApi';
export default function App() {
return (
<RestApi/>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
color: 'white',
alignItems: 'center',
justifyContent: 'center',
}
})
This is my code RestApi.js
import axios from 'axios';
import React, { useState, useEffect } from 'react'
import { Button, Flatlist, SafeAreaView, ScrollView, StyleSheet, Text, TextInput, TouchableOpacity, View } from 'react-native';
export default function RestApi() {
const [title, setTitle] = useState("");
const [value,setValue] = useState("");
const [items, setItems] = useState([]);
const [button, setButton] = useState("Simpan");
const [selectedUser, setSelectedUser] = useState({});
const submit =()=>{
const data = {
value,title
}
//console.log(data)
if(button=="Simpan"){
axios.post('https://achmadhilmy-sanbercode.my.id/api/v1/news', data)
.then(res=>{
console.log('res: ', res)
setTitle("")
setValue("")
GetData()
}).catch(err=>{
console.log('error: ',err)
})
}else{
axios.put(`https://achmadhilmy-sanbercode.my.id/api/v1/news/${selectedUser.id}`, data)
.then(res=>{
console.log('res: ',res)
setTitle("")
setValue("")
GetData()
setButton("Simpan")
}).catch(err=>{
console.log('error: ', err)
})
}
}
const onSelectItem = (item)=>{
console.log(item)
setSelectedUser(item)
setTitle(item.title)
setValue(item.value)
setButton("Update")
}
const GetData=()=>{
axios.get('https://achmadhilmy-sanbercode.my.id/api/v1/news')
.then(res=>{
const data1 = (res.data.data)
console.log('res: ', data1)
setItems(data1)
})
}
const onDelete=(item)=>{
axios.delete(`https://achmadhilmy-sanbercode.my.id/api/v1/news/${item.id}`)
.then(res=>{
console.log('res: ', res)
GetData()
}).catch(err=>{
console.log('error: ', err)
})
}
useEffect(() => {
GetData()
}, [])
return (
<View style={styles.container}>
<View style={styles.header}>
<Text style={styles.title}>Tampilkan Api (CRUD)</Text>
</View>
<View style={styles.content1}>
<Text>Post Data</Text>
<TextInput
placeholder="Masukan judul berita"
style={styles.input}
value={title}
onChangeText={(value)=>setTitle(value)}
/>
<TextInput
placeholder="Masukan Isi berita"
style={styles.input}
value={value}
onChangeText={(value)=>setValue(value)}
/>
<Button
title={button}
onPress={submit}
/>
</View>
<View style={styles.content1}>
<Text>Get Data Berita</Text>
<Flatlist
data={items}
keyExtractor={(item, index) => `${item.id}-${index}`}
renderItem={({item})=>{
return (
<View>
<TouchableOpacity onPress={()=>onDelete(item)}>
<Text style={{color: 'red', alignSelf: 'flex-end'}}>X</Text>
</TouchableOpacity>
<TouchableOpacity onPress={()=>onSelectItem(item)}style={{borderRadius: 6,backgroundColor:'grey', padding: 5, marginBottom:10}}>
<Text style={{color: 'white'}}>{item.title}</Text>
<Text style={{color: 'white'}}>{item.value}</Text>
</TouchableOpacity>
</View>
)
}}
/>
</View>
</View>
)
}
const styles = StyleSheet.create({
container:{
flex:1,
backgroundColor:'white'
},
header:{
paddingTop: 50,
paddingHorizontal: 16,
backgroundColor: 'grey',
alignItems: 'center'
},
title:{
color: 'white',
fontSize: 20
},
content1:{
paddingHorizontal: 16
},
input:{
borderWidth:1,
paddingVertical: 10,
paddingHorizontal: 5,
borderRadius: 6,
marginTop: 10
},
contentNews:{
backgroundColor:'grey',
paddingVertical:10
}
})
Your RestApi component does return anything, because the return statement is nested within the submit function, but that does not get called.
Could you try unnesting the return statement? See example below, where I also unnested the useEffect call and several other functions.
import axios from 'axios'
import React, { useState, useEffect } from 'react'
import {
Button,
Flatlist,
SafeAreaView,
ScrollView,
StyleSheet,
Text,
TextInput,
TouchableOpacity,
View
} from 'react-native'
export default function RestApi() {
const [title, setTitle] = useState('')
const [value, setValue] = useState('')
const [items, setItems] = useState([])
const [button, setButton] = useState('Simpan')
const [selectedUser, setSelectedUser] = useState({})
const submit = () => {
const data = {
value,
title
}
//console.log(data)
if (button == 'Simpan') {
axios
.post('https://achmadhilmy-sanbercode.my.id/api/v1/news', data)
.then(res => {
console.log('res: ', res)
setTitle('')
setValue('')
GetData()
})
.catch(err => {
console.log('error: ', err)
})
} else {
axios
.put(
`https://achmadhilmy-sanbercode.my.id/api/v1/news/${selectedUser.id}`,
data
)
.then(res => {
console.log('res: ', res)
setTitle('')
setValue('')
GetData()
setButton('Simpan')
})
.catch(err => {
console.log('error: ', err)
})
}
}
const onSelectItem = item => {
console.log(item)
setSelectedUser(item)
setTitle(item.title)
setValue(item.value)
setButton('Update')
}
const GetData = () => {
axios
.get('https://achmadhilmy-sanbercode.my.id/api/v1/news')
.then(res => {
const data1 = res.data.data
console.log('res: ', data1)
setItems(data1)
})
}
const onDelete = item => {
axios
.delete(
`https://achmadhilmy-sanbercode.my.id/api/v1/news/${item.id}`
)
.then(res => {
console.log('res: ', res)
GetData()
})
.catch(err => {
console.log('error: ', err)
})
}
useEffect(() => {
GetData()
}, [])
return (
<View style={styles.container}>
<View style={styles.header}>
<Text style={styles.title}>Tampilkan Api (CRUD)</Text>
</View>
<View style={styles.content1}>
<Text>Post Data</Text>
<TextInput
placeholder="Masukan judul berita"
style={styles.input}
value={title}
onChangeText={value => setTitle(value)}
/>
<TextInput
placeholder="Masukan Isi berita"
style={styles.input}
value={value}
onChangeText={value => setValue(value)}
/>
<Button title={button} onPress={submit} />
</View>
<View style={styles.content1}>
<Text>Get Data Berita</Text>
<Flatlist
data={items}
keyExtractor={(item, index) => `${item.id}-${index}`}
renderItem={({ item }) => {
return (
<View>
<TouchableOpacity
onPress={() => onDelete(item)}>
<Text
style={{
color: 'red',
alignSelf: 'flex-end'
}}>
X
</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={() => onSelectItem(item)}
style={{
borderRadius: 6,
backgroundColor: 'grey',
padding: 5,
marginBottom: 10
}}>
<Text style={{ color: 'white' }}>
{item.title}
</Text>
<Text style={{ color: 'white' }}>
{item.value}
</Text>
</TouchableOpacity>
</View>
)
}}
/>
</View>
</View>
)
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: 'white'
},
header: {
paddingTop: 50,
paddingHorizontal: 16,
backgroundColor: 'grey',
alignItems: 'center'
},
title: {
color: 'white',
fontSize: 20
},
content1: {
paddingHorizontal: 16
},
input: {
borderWidth: 1,
paddingVertical: 10,
paddingHorizontal: 5,
borderRadius: 6,
marginTop: 10
},
contentNews: {
backgroundColor: 'grey',
paddingVertical: 10
}
})

How to save route.params with asyncstorage?

Srry if the title makes no sense. Don't know a better title.
How can I save route.params items that I pass to my second screen using AsyncStorage?
In my first screen i have a bunch of data in a FlatList that can be opened with a Modal. Inside that Modal I have a TouchableOpacity that can send the data thats inside the Modal to my second screen. The data that has been passed to the second screen is passed to a FlatList. The data in the FlatList should be saved to AsyncStorage. Tried alot of things getting this to work, but only getting warning message
undefined. Code below is the most recent progress.
Using React Navigation V5.
FIRST SCREEN
const [masterDataSource, setMasterDataSource] = useState(DataBase);
const [details, setDetails] = useState('');
<TouchableOpacity
onPress={() => {
const updated = [...masterDataSource];
updated.find(
(item) => item.id === details.id,
).selected = true;
setMasterDataSource(updated);
navigation.navigate('cart', {
screen: 'cart',
params: {
items: updated.filter((item) => item.selected),
},
});
setModalVisible(false);
}}>
<Text>Add to cart</Text>
</TouchableOpacity>
SECOND SCREEN
import React, { useEffect, useState } from 'react';
import { View, Text, FlatList, TouchableOpacity } from 'react-native';
import { useTheme } from '../Data/ThemeContext';
import AsyncStorage from '#react-native-async-storage/async-storage';
import Ionicons from 'react-native-vector-icons/Ionicons';
export default function ShoppingList({ route, navigation }) {
const [shoppingList, setShoppingList] = useState([]);
const { colors } = useTheme();
const todo = () => {
alert('Todo');
};
useEffect(() => {
restoreShoppingListAsync();
}, []);
const shoppingListAsync = () => {
const shoppingList = route.params && route.params.items;
setShoppingList(list);
storeShoppingList(list);
};
const asyncStorageKey = '#ShoppingList';
const storeShoppingListAsync = (list) => {
const stringifiedList = JSON.stringify(list);
AsyncStorage.setItem(asyncStorageKey, stringifiedList).catch((err) => {
console.warn(err);
});
};
const restoreShoppingListAsync = () => {
AsyncStorage.getItem(asyncStorageKey)
.then((stringifiedList) => {
console.log(stringifiedList);
const parsedShoppingList = JSON.parse(stringifiedList);
if (!parsedShoppingList || typeof parsedShoppingList !== 'object')
return;
setShoppingList(parsedShoppingList);
})
.then((err) => {
console.warn(err);
});
};
const RenderItem = ({ item }) => {
return (
<View>
<TouchableOpacity
style={{
marginLeft: 20,
marginRight: 20,
elevation: 3,
backgroundColor: colors.card,
borderRadius: 10,
}}>
<View style={{ margin: 10 }}>
<Text style={{ color: colors.text, fontWeight: '700' }}>
{item.name}
</Text>
<Text style={{ color: colors.text }}>{item.gluten}</Text>
<Text style={{ color: colors.text }}>{item.id}</Text>
</View>
</TouchableOpacity>
</View>
);
};
const emptyComponent = () => {
return (
<View style={{ alignItems: 'center' }}>
<Text style={{ color: colors.text }}>Listan är tom</Text>
</View>
);
};
const itemSeparatorComponent = () => {
return (
<View
style={{
margin: 3,
}}></View>
);
};
return (
<View
style={{
flex: 1,
}}>
<View
style={{
padding: 30,
backgroundColor: colors.Textinput,
elevation: 12,
}}>
<View style={{ flexDirection: 'row', justifyContent: 'space-between' }}>
<TouchableOpacity onPress={() => navigation.goBack()}>
<Ionicons name="arrow-back-outline" size={25} color="#fff" />
</TouchableOpacity>
<Text style={{ color: '#fff', fontSize: 20 }}>Inköpslista</Text>
<TouchableOpacity>
<Ionicons
name="trash-outline"
size={25}
color="#fff"
onPress={() => todo()}
/>
</TouchableOpacity>
</View>
</View>
<View style={{ flex: 1, marginTop: 30 }}>
<FlatList
data={shoppingList}
renderItem={RenderItem}
ListEmptyComponent={emptyComponent}
ItemSeparatorComponent={itemSeparatorComponent}
initialNumToRender={4}
maxToRenderPerBatch={5}
windowSize={10}
removeClippedSubviews={true}
updateCellsBatchingPeriod={100}
showsVerticalScrollIndicator={true}
contentContainerStyle={{ paddingBottom: 20 }}
/>
</View>
</View>
);
}
As you are using async storage to maintain the cart.
I would suggest an approach as below
Update the asyn storage when new items are added to or removed from the cart
Retrieve the items from the cart screen and show the items there
Before you navigate store the items like below
AsyncStorage.setItem(
'Items',
JSON.stringify(updated.filter((item) => item.selected))
).then(() => {
navigation.navigate('Cart', {
items: updated.filter((item) => item.selected),
});
});
The cart screen would be something like below
function Cart({ navigation, route }) {
const [data,setData]=useState([]);
React.useEffect(() => {
async function fetchMyAPI() {
const value = await AsyncStorage.getItem('Items');
setData(JSON.parse(value));
}
fetchMyAPI();
}, []);
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Button title="Go back" onPress={() => navigation.goBack()} />
<FlatList
data={data}
renderItem={RenderItem}
/>
</View>
);
}
Working Example
https://snack.expo.io/#guruparan/cartexample

How can i get back my data list after searching by words?

i use Flatlist and search by words on renderHeader() function. I can filter but when i delete letters, i couldn't get main list again. I think there is a logic problem but i couln't find after trying something...
i've got a new one when i fixed problem. I tried to fix but i couldn't do that, i should put the problem in front of experts :)
import React, {Component, useState} from 'react'
import {
Text,
StyleSheet,
View,
FlatList,
SafeAreaView,
ScrollView,
Image,
TextInput,
} from 'react-native'
import data from '../../data'
const Flatlistexample = () => {
//main list state
let [list, setList] = useState(data);
//search state
const [search, setSearch] = useState('');
//search filter
searchFilter = text => {
// onChangeText
const newData = list.filter(item => {
const listItem = `${item.name.toLowerCase()} ${item.company.toLowerCase()}`
return listItem.indexOf(text.toLowerCase()) > -1;
})
setList(newData)
}
//search function
renderHeader = () =>{
return (
<View style={styles.seachContainer}>
<TextInput
style={styles.textInput}
placeholder={'Search...'}
value={search}
onChangeText={text => {
//setStates
searchFilter(text)
setSearch(text)
}}></TextInput>
<Text
style={{
alignItems: 'flex-start',
color: 'black',
fontSize: 22,
}}>
{search}
</Text>
</View>
)
}
return (
<SafeAreaView
style={{
flex: 1,
}}>
<FlatList
data={list}
renderItem={({item, index}) => {
return (
<ScrollView>
<SafeAreaView
style={[
styles.container,
{backgroundColor: index % 2 === 0 ? '#fafafa' : '#bbb'},
]}>
<Image style={styles.profile} source={{uri: item.picture}} />
<View style={styles.rightside}>
<Text style={styles.name}>{item.name}</Text>
<Text style={styles.company}>{item.company}</Text>
</View>
</SafeAreaView>
</ScrollView>
)
}}
keyExtractor={item => item._id}
//called search function
ListHeaderComponent={renderHeader()}
/>
</SafeAreaView>
)
}
export default Flatlistexample
const styles = StyleSheet.create({
container: {
flexDirection: 'row',
alignItems: 'center',
borderBottomWidth: 1,
borderColor: 'gray',
},
profile: {
width: 50,
height: 50,
borderRadius: 25,
marginLeft: 10,
},
rightside: {
marginLeft: 20,
justifyContent: 'space-between',
marginVertical: 5,
},
name: {
fontSize: 22,
marginBottom: 10,
},
searchContainer: {
padding: 10,
borderWidth: 2,
borderColor: 'gray',
},
textInput: {
fontSize: 16,
backgroundColor: '#f9f9f9',
padding: 10,
},
})
Thanks for your help
Filter Data
onSearchText = (value) => {
this.setState({searchText: value})
if(value.trim() == "" || value == null){
this.setState({list: this.state.list}
} else {
let filter = this.state.list.fillter(data => {
// data fillter logic //
return data;
})
this.setState({filterData: filter})
}
Render FlatList
<FlatList
extradata={this.state}
data={searchText ? filterData : list}
/>
I fixed...
How?
My main data state is constant, i'm filtering on data list with filter state. So my data list doesn't change anytime.
import React, {Component, useState} from 'react'
import {
Text,
StyleSheet,
View,
FlatList,
SafeAreaView,
ScrollView,
Image,
TextInput,
} from 'react-native'
import data from '../../data'
const Flatlistexample = () => {
//main list state
let [list, setList] = useState(data)
//search state
const [search, setSearch] = useState('')
//filter state
const [updated, setUpdated] = useState(data)
//search filter
searchFilter = text => {
// onChangeText
if (text) {
const newData = list.filter(item => {
const listItem = `${item.name.toLowerCase()} ${item.company.toLowerCase()}`
return listItem.indexOf(text.toLowerCase()) > -1
})
setUpdated(newData)
}
//search function
renderHeader = () => {
return (
<View style={styles.seachContainer}>
<TextInput
style={styles.textInput}
placeholder={'Search...'}
value={search}
onChangeText={text => {
searchFilter(text)
setSearch(text)
}}></TextInput>
<Text
style={{
alignItems: 'flex-start',
color: 'black',
fontSize: 22,
}}>
{search}
</Text>
</View>
)
}
return (
<SafeAreaView
style={{
flex: 1,
}}>
<FlatList
//i'm showing filter state
data={updated}
renderItem={({item, index}) => {
return (
<ScrollView>
<SafeAreaView
style={[
styles.container,
{backgroundColor: index % 2 === 0 ? '#fafafa' : '#bbb'},
]}>
<Image style={styles.profile} source={{uri: item.picture}} />
<View style={styles.rightside}>
<Text style={styles.name}>{item.name}</Text>
<Text style={styles.company}>{item.company}</Text>
</View>
</SafeAreaView>
</ScrollView>
)
}}
keyExtractor={item => item._id}
//called search function
ListHeaderComponent={renderHeader()}
/>
</SafeAreaView>
)
}
export default Flatlistexample
const styles = StyleSheet.create({
container: {
flexDirection: 'row',
alignItems: 'center',
borderBottomWidth: 1,
borderColor: 'gray',
},
profile: {
width: 50,
height: 50,
borderRadius: 25,
marginLeft: 10,
},
rightside: {
marginLeft: 20,
justifyContent: 'space-between',
marginVertical: 5,
},
name: {
fontSize: 22,
marginBottom: 10,
},
searchContainer: {
padding: 10,
borderWidth: 2,
borderColor: 'gray',
},
textInput: {
fontSize: 16,
backgroundColor: '#f9f9f9',
padding: 10,
},
})
/*
else if(text.length > uzunluk){
setList(data)
const newData = list.filter(item => {
const listItem = `${item.name.toLowerCase()} ${item.company.toLowerCase()}`
return listItem.indexOf(text.toLowerCase()) > -1;
})
setList(newData)
}else if(text.length<uzunluk){
setList(data)
const newData = list.filter(item => {
const listItem = `${item.name.toLowerCase()} ${item.company.toLowerCase()}`
return listItem.indexOf(text.toLowerCase()) > -1;
})
setList(newData)
}
*/

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

Categories

Resources