React Native useState not auto Updating? - react-native

why useState auto update? I'll press button and not showing textinput. but I can save file without change. textinput will be showing. sorry my bad english
import React, { useState,useEffect } from 'react';
import {Text, TextInput, View, Button,} from 'react-native';
const Test = ({navigation}) => {
const [textInput, settextInput] = useState([]);
useEffect(() => {
addTextInput = (key) => {
textInput.push([<TextInput style={{backgroundColor :'#7ACB4A',marginTop:10}} key={key} />]);
settextInput(textInput);
console.log(textInput);
}
},[textInput]);
return(
<View>
<Button title='+' onPress={() =>
addTextInput(textInput.length)} />
{textInput.map((value, index) => {
return value
})}
<Text>{textInput.length}</Text>
</View>
);
}
export default Test;

I have a few suggests to make your code better.
Don't change state value if not in use 'setState'.
This is false by nature and causes errors.
addTextInput = (key) => {
textInput.push([<TextInput style={{backgroundColor :'#7ACB4A',marginTop:10}} key={key} />]);
settextInput(textInput);
console.log(textInput);
}
State merely contains value, it should not contain different things. You should return TextInput in your map function.
I try rewrite your code, sorry because my english. Hope help you
code:
const [textInput, setTextInput] = React.useState(['1', '2'])
const addTextInput = (key: string) => {
const tempInput = textInput.concat([key])
setTextInput(tempInput)
}
return (
<View style={{ alignItems: 'center', justifyContent: 'center', flex: 1 }}>
<Button title="+" onPress={() => addTextInput(textInput.length.toString())} />
{textInput.map((value, index) => {
return (
<TextInput style={{ backgroundColor: '#7ACB4A', marginTop: 10, width: '70%' }} key={index + ''} />
)
})}
<Text>{textInput.length}</Text>
</View>
)
}

Related

Nested lists - How to modify (delete, add, update) items from a nested list using item's buttons and useState?

My first idea was to try to delete items from a nested list. I've started using SectionList and a component that has an useState that manages the data changes of the SectionList. I'm trying to solve it using SectionList but it'd be great to display all possible alternatives (FlatList, ViewList, etc).
I figured out how to delete a whole section list (and his items) but not one item by one. I've read plenty of posts, but I did find nothing related to managing SectionList items. Maybe there's an answer out there for FlatList nested items.
Here I left an example code ready to use (without styles) based on React Native official docs:
import React, { useEffect } from "react";
import { StyleSheet, Text, View, SafeAreaView, SectionList, StatusBar, Button } from "react-native";
import { useState } from "react";
const dataResource = [
{
title: "Main dishes",
data: ["Pizza", "Burger", "Risotto"],
n: "delete",
k: 1
},
{
title: "Sides",
data: ["French Fries", "Onion Rings", "Fried Shrimps"],
n: "delete",
k: 2
},
];
function App() {
const [state, setState] = useState(dataResource)
const Item = ({ dish, obj, i}) => (
<View >
<Text >{dish} </Text>
<Button title={obj.n} onPress={() => {}} /> // add the handler
</View>
);
const SectionComponent = ({ t, k }) => (
<View>
<Text >{t} </Text>
<Button title={'section'} onPress={() => { setState(state.filter(e => e.k != k)) }} />
</View>
);
return (
<SafeAreaView >
<SectionList
sections={state}
keyExtractor={(item, index) => item + index}
renderItem={({ item, section, index}) => <Item dish={item} obj={section} i={index}/>}
renderSectionHeader={({ section: { title, k } }) => <SectionComponent k={k} t={title} />}
/>
</SafeAreaView>
);
}
export default App;
I think how you display the data is trivial. The component you use will just change how you access the data, not how you update it. What you need is helper functions for editing the data. With those in place you can do things like add/remove section items, and editing section items themselves:
import React, { useState } from 'react';
import {
Text,
View,
StyleSheet,
SafeAreaView,
SectionList,
Button,
TextInput,
} from 'react-native';
const dataResource = [
{
title: 'Main dishes',
data: ['Pizza', 'Burger', 'Risotto'],
id: 1,
},
{
title: 'Sides',
data: ['French Fries', 'Onion Rings', 'Fried Shrimps'],
id: 2,
},
];
export default function App() {
const [state, setState] = useState(dataResource);
const [sectionTitle,setSectionTitle] = useState('Drinks')
const editItem = (itemId, newValue) => {
let newState = [...state];
let itemIndex = newState.findIndex((item) => item.id == itemId);
if (itemIndex < 0) return;
newState[itemIndex] = {
...newState[itemIndex],
...newValue,
};
setState(newState);
};
const addSectionItem = (title)=>{
let newState = [...state]
newState.push({
title,
data:[],
id:newState.length+1
})
setState(newState)
}
const removeFood = (itemId, food) => {
let currentItem = state.find((item) => item.id == itemId);
console.log(currentItem);
currentItem.data = currentItem.data.filter((item) => item != food);
console.log(currentItem.data);
editItem(itemId, currentItem);
};
const addFood = (itemId, food) => {
let currentItem = state.find((item) => item.id == itemId);
console.log(currentItem.data);
currentItem.data.push(food);
console.log(currentItem.data);
editItem(itemId, currentItem);
};
const Item = ({ item, section, index }) => {
return (
<View style={styles.row}>
<Text>{item} </Text>
<Button
title={'Delete'}
onPress={() => {
removeFood(section.id, item);
}}
/>
</View>
);
};
const SectionHeader = ({ title, id }) => {
return (
<View style={styles.header}>
<Text style={{ fontSize: 18 }}>{title} </Text>
<Button
title={'X'}
onPress={() => {
setState(state.filter((e) => e.id != id));
}}
/>
</View>
);
};
const SectionFooter = ({ id }) => {
const [text, setText] = useState('');
return (
<View style={[styles.row, styles.inputWrapper]}>
<Text>Add Entry</Text>
<TextInput
value={text}
onChangeText={setText}
style={{ borderBottomWidth: 1 }}
/>
<Button title="Add" onPress={() => addFood(id, text)} />
</View>
);
};
return (
<SafeAreaView>
<Button title="Reset list" onPress={() => setState(dataResource)} />
<View style={[styles.row, styles.inputWrapper]}>
<Text>Add New Section</Text>
<TextInput
value={sectionTitle}
onChangeText={setSectionTitle}
style={{ borderBottomWidth: 1 }}
/>
<Button title="Add" onPress={() => addSectionItem(sectionTitle)} />
</View>
<View style={styles.sectionListWrapper}>
<SectionList
sections={state}
keyExtractor={(item, index) => item + index}
renderItem={Item}
renderSectionHeader={({ section }) => <SectionHeader {...section} />}
renderSectionFooter={({ section }) => <SectionFooter {...section} />}
/>
</View>
</SafeAreaView>
);
}
const styles = StyleSheet.create({
row: {
flexDirection: 'row',
width: '100%',
justifyContent: 'space-between',
padding: 5,
alignItems: 'center',
},
header: {
flexDirection: 'row',
paddingVertical: 5,
width: '100%',
borderBottomWidth: 1,
},
inputWrapper: {
paddingVertical: 15,
marginBottom: 10,
},
sectionListWrapper: {
padding: 5,
},
});
Here's a demo
I've improved my answer to give a clearer example of how to manipulate SectionList. An example of how to add/delete/modify sections and its data is provided.
import React from 'react';
export default function useStateHelpers(state, setState) {
const editSection = (sectionId, newValue) => {
// parse and stringify is used to clone properly
let newState = JSON.parse(JSON.stringify(state));
let itemIndex = newState.findIndex((item) => item.id == sectionId);
if (itemIndex < 0) return;
const section = {
...newState[itemIndex],
...newValue,
};
newState[itemIndex] = section;
setState(newState);
};
const editSectionDataItem = (sectionId, itemId, newValue) => {
const newState = JSON.parse(JSON.stringify(state));
const sectionIndex = newState.findIndex(
(section) => section.id == sectionId
);
const section = newState[sectionIndex];
const itemIndex = section.data.findIndex((item) => item.id == itemId);
let item = section.data[itemIndex];
section.data[itemIndex] = {
...item,
...newValue,
};
editSection(sectionId, section);
};
const editSectionTitle = (sectionId, title) =>
editSection(sectionId, { title });
const setSelectSectionItem = (sectionId, itemId, isSelected) => {
editSectionDataItem(sectionId, itemId, { isSelected });
};
const removeSectionDataItem = (sectionId, food) => {
let newState = JSON.parse(JSON.stringify(state));
let sectionIndex = newState.findIndex((section) => section.id == sectionId);
let section = newState[sectionIndex];
section.data = section.data.filter((item) => item.title != food);
editSection(sectionId, section);
};
const addSectionDataItem = (sectionId, title, price) => {
let newState = JSON.parse(JSON.stringify(state));
let sectionIndex = newState.findIndex((section) => section.id == sectionId);
let section = newState[sectionIndex];
section.data.push({
title,
price,
id: `section-${sectionId}-${section.data.length + 1}`,
});
editSection(sectionId, section);
};
const addSection = (title, data = [], id) => {
let newState = JSON.parse(JSON.stringify(state));
newState.push({
title,
data,
id: newState.length + 1,
});
setState(newState);
};
const helpers = {
editSection,
editSectionTitle,
removeSectionDataItem,
addSectionDataItem,
addSection,
setSelectSectionItem,
editSectionDataItem,
};
return helpers;
}
import React, { useState } from 'react';
import {
StyleSheet,
SafeAreaView,
View,
Button,
SectionList,
} from 'react-native';
import data from './data';
import StateContext from './StateContext';
import useStateHelpers from './hooks/useStateHelpers';
import Header from './components/SectionHeader';
import Footer from './components/SectionFooter';
import Item from './components/SectionItem';
import TextInput from './components/Input';
export default function App() {
const [state, setState] = useState(data);
const [sectionTitle, setSectionTitle] = useState('');
const helpers = useStateHelpers(state, setState);
return (
<SafeAreaView style={{ flex: 1 }}>
<StateContext.Provider value={{ state, setState, ...helpers }}>
<View style={styles.container}>
<Button title="Reset list" onPress={()=>setState(data)} />
<TextInput
label={'Add New Section'}
value={sectionTitle}
onChangeText={setSectionTitle}
onRightIconPress={() => {
helpers.addSection(sectionTitle);
setSectionTitle('');
}}
/>
<View style={styles.sectionListWrapper}>
<SectionList
style={{ flex: 1 }}
sections={state}
renderItem={(props) => <Item {...props} />}
renderSectionHeader={(props) => <Header {...props} />}
renderSectionFooter={(props) => <Footer {...props} />}
/>
</View>
</View>
</StateContext.Provider>
</SafeAreaView>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 8,
},
sectionListWrapper: {
padding: 5,
flex: 1,
},
});
import React, { useContext } from 'react';
import { View, TouchableOpacity, StyleSheet, Text, Button } from 'react-native';
import StateContext from '../StateContext';
export default function Item({ item, section, index }) {
const {
removeSectionDataItem,
setSelectSectionItem
} = useContext(StateContext);
const hasPrice = item.price.toString().trim().length > 0;
return (
<TouchableOpacity
style={[styles.container, item.isSelected && styles.selectedContainer]}
onPress={() =>
setSelectSectionItem(section.id, item.id, !item.isSelected)
}
>
<View style={styles.row}>
<Text>
{item.title + (hasPrice ? ' | ' : '')}
{hasPrice && <Text style={{ fontWeight: '300' }}>{item.price}</Text>}
</Text>
<Button
title={'Delete'}
onPress={() => {
removeSectionDataItem(section.id, item.title);
}}
/>
</View>
</TouchableOpacity>
);
}
const styles = StyleSheet.create({
container: {
marginVertical: 2,
},
selectedContainer: {
backgroundColor: 'rgba(0,0,0,0.2)',
},
row: {
flexDirection: 'row',
width: '100%',
justifyContent: 'space-between',
padding: 5,
alignItems: 'center',
},
});
/*SectionFooter.js*/
import React, { useState, useContext, useEffect } from 'react';
import { View, StyleSheet, Text } from 'react-native';
import TextInput from './Input';
import StateContext from '../StateContext';
export default function SectionFooter({ section }) {
const [title, setTitle] = useState('');
const [price, setPrice] = useState('');
const [titleWasEdited, setTitleWasEdited] = useState(false);
const { addSectionDataItem, editSectionDataItem } = useContext(StateContext);
const selectedItem = section.data.find((item) => item.isSelected);
// listen for item selection
useEffect(() => {
// pass item values to text input
setTitle(selectedItem?.title || '');
setPrice(selectedItem?.price || '');
// reset title/price input
setTitleWasEdited(false);
}, [selectedItem]);
return (
<View style={styles.container}>
<Text>
{selectedItem
? 'Editing ' + selectedItem.title
: 'Add New Entry'
}
</Text>
{/*one input handles both title and price*/}
<TextInput
label={titleWasEdited ? 'Price' : 'Title'}
value={titleWasEdited ? price : title}
onChangeText={titleWasEdited ? setPrice : setTitle}
rightIconName={titleWasEdited ? 'plus' : 'arrow-right'}
// rightIcon is disabled when theres no text
// but price is allowed to be empty
allowEmptySubmissions={titleWasEdited}
style={{ width: '80%' }}
onRightIconPress={() => {
// after title is edited allow submission
if (titleWasEdited) {
// if item was edited update it
if (selectedItem) {
editSectionDataItem(section.id, selectedItem.id, {
title,
price,
isSelected: false,
});
}
// or add new item
else {
addSectionDataItem(section.id, title, price);
}
setTitle('');
setPrice('');
}
// toggle between title & price
setTitleWasEdited((prev) => !prev);
}}
/>
</View>
);
}
const styles = StyleSheet.create({
container: {
marginVertical: 20,
alignItems: 'center',
},
});
import React, { useContext } from 'react';
import { View, StyleSheet } from 'react-native';
import { TextInput } from 'react-native-paper';
import StateContext from '../StateContext';
export default function SectionHeader({ section: { id, title } }) {
const { editTitle, setState, state } = useContext(StateContext);
return (
<View style={{ borderBottomWidth: 1 }}>
<View style={styles.header}>
<TextInput
style={styles.titleInput}
value={title}
onChangeText={(text) => {
editTitle(id, text);
}}
right={
<TextInput.Icon
name="close"
onPress={() => {
setState(state.filter((sec) => sec.id != id));
}}
/>
}
underlineColor="transparent"
activeUnderlineColor="transparent"
outlineColor="transparent"
activeOutlineColor="transparent"
selectionColor="transparent"
dense
/>
</View>
</View>
);
}
const styles = StyleSheet.create({
header: {
flexDirection: 'row',
width: '100%',
justifyContent: 'space-around',
alignItems: 'center',
},
titleInput: {
fontSize: 18,
backgroundColor: 'transparent',
borderWidth: 0,
borderColor: 'transparent',
height: 36,
},
});

react native recyclerlistview if state changed its scroll to top

If I change any state or change the textinput value, if it changed then its scroll to top and leave the textinput. Or If I like one product, its autoamticlly scroll to top if the array is changed. Anyone can help me ?
import React, { useState, useMemo, useEffect, forwardRef, memo } from 'react';
import { StyleSheet, Text, TextInput, View, TouchableOpacity, Image, Dimensions } from 'react-native';
import { TouchableWithoutFeedback } from 'react-native-gesture-handler';
import { RecyclerListView, LayoutProvider, DataProvider } from 'recyclerlistview';
import { useSelector, useDispatch } from 'react-redux';
import { AntDesign } from '#expo/vector-icons';
import { addAmountOnCartItem } from '../../../redux/slice/product/shopping_cart';
import faker from 'faker';
import ButtonWithoutLoader from '../../ButtonWithoutLoader';
const { width, height } = Dimensions.get('window');
const Shopping_cart_list = ({ datas, onPressSetting }) => {
const dispatch = useDispatch();
const provider = useMemo(() => {
return new DataProvider(
(r1, r2) => {
return r1 !== r2;
},
index => {
return 'id:' + index;
}
)
}, []);
const dataProvider = useMemo(() => {
return provider.cloneWithRows(datas);
}, [datas, provider]);
const [update, updateRecycler] = useState({
update: false
});
const handleChange = (e, product_id) => {
dispatch(addAmountOnCartItem({ value: e, product_id }));
updateRecycler(prevState => {
return {
update: !prevState
}
});
};
const layoutProvider = new LayoutProvider((i) => {
return dataProvider.getDataForIndex(i).type;
}, (type, dim) => {
switch(type) {
case 'NORMAL':
dim.height = 250;
dim.width = width * 0.9;
break;
default:
dim.height = 0;
dim.width = 0;
break;
}
});
const RenderData = memo(({ product_id, product_name, price, product_image, amount, username }) => {
return (
<TouchableWithoutFeedback style={{height: 250, backgroundColor: '#fff', marginBottom: 16}}>
<View style={styles.header}>
<TouchableOpacity style={styles.profile_info}>
<Image source={{uri: faker.image.avatar()}} resizeMode="contain" style={styles.profile_image} />
<Text style={styles.username}>{ username }</Text>
</TouchableOpacity>
<TouchableOpacity onPress={() => onPressSetting(product_id)}>
<AntDesign name="setting" size={24} color="#444" />
</TouchableOpacity>
</View>
<View style={styles.mainContainer}>
<Image source={{uri: product_image}} style={styles.image} />
<View>
<Text style={styles.text}>{product_name}</Text>
<Text style={styles.text}>Preis: {price}</Text>
<View style={{flexDirection: 'row', alignItems: 'center'}}>
<Text style={styles.text}>Anzahl: </Text>
<AntDesign name="minussquareo" style={{marginRight: 6}} size={24} color="black" />
<TextInput onBlur={() => handleChange(1, product_id)} value={ isNaN(amount) ? '' : amount.toString() } onChangeText={e => handleChange(e, product_id)} style={{height: 28, width: 28, borderRadius: 4, textAlign: 'center', backgroundColor: '#eee'}} />
<AntDesign name="plussquareo" style={{marginLeft: 6}} size={24} color="black" />
</View>
</View>
</View>
<View style={[styles.header, { marginTop: 4 }]}>
<ButtonWithoutLoader onPress={() => updateRecycler(prevState => !prevState)} title="Jetzt Kaufen!" width={width * 0.9} />
</View>
</TouchableWithoutFeedback>
)
});
const rowRenderer = (type, data) => {
const { product_id, product_name, price, product_image, amount, username } = data.item;
return <RenderData product_id={product_id} product_name={product_name} price={price} product_image={product_image} amount={amount} username={username} />
};
return (
<View style={{flex: 1, paddingBottom: 85}}>
<RecyclerListView
dataProvider={dataProvider}
layoutProvider={layoutProvider}
forceNonDeterministicRendering={true}
rowRenderer={rowRenderer}
style={{marginLeft: width * 0.05, marginRight: width * 0.05}}
extendedState={update}
scrollViewProps={{showsVerticalScrollIndicator: false}}
/>
</View>
)
};
Flatlist:
import React, { useState, useRef, memo, useMemo } from 'react';
import { StyleSheet, Animated, FlatList, Text, TextInput, View, TouchableOpacity, Image, Dimensions } from 'react-native';
import { TouchableWithoutFeedback } from 'react-native-gesture-handler';
import { useSelector, useDispatch } from 'react-redux';
import { useNavigation } from '#react-navigation/core';
import { AntDesign } from '#expo/vector-icons';
import { addAmountOnCartItem } from '../../../redux/slice/product/shopping_cart';
import faker from 'faker';
import ButtonWithoutLoader from '../../ButtonWithoutLoader';
const { width } = Dimensions.get('window');
const Shopping_cart = ({ datas, onPressSetting }) => {
const dispatch = useDispatch();
const navigation = useNavigation();
const [update, updateRecycler] = useState({
update: false
});
const handleChange = (e, product_id) => {
dispatch(addAmountOnCartItem({ value: e, product_id }));
updateRecycler(prevState => {
return {
update: !prevState
}
});
};
const RenderItem = memo(({ item }) => {
const { product_id, product_name, price, product_image, amount, username, size, colors, desc, selectedColor, selectedSize } = item.item;
return (
<TouchableWithoutFeedback style={{height: 300, backgroundColor: '#fff', marginBottom: 16}}>
<View style={styles.header}>
<TouchableOpacity style={styles.profile_info}>
<Image source={{uri: faker.image.avatar()}} resizeMode="contain" style={styles.profile_image} />
<Text style={styles.username}>{ username }</Text>
</TouchableOpacity>
<TouchableOpacity onPress={() => onPressSetting(product_id)}>
<AntDesign name="setting" size={24} color="#444" />
</TouchableOpacity>
</View>
<TouchableOpacity onPress={() => navigation.navigate('ProductStack', {
product_id,
desc,
price,
product_image,
username,
user_profil_image: faker.image.avatar(),
size,
colors,
})} style={styles.mainContainer}>
<Image source={{uri: product_image}} style={styles.image} />
<View>
<Text style={styles.text}>{product_name}</Text>
<Text style={styles.text}>Preis: {price}</Text>
<Text style={styles.text}>Farbe: {selectedColor}</Text>
<Text style={styles.text}>Größe: {selectedSize}</Text>
<View style={{flexDirection: 'row', alignItems: 'center'}}>
<Text style={styles.text}>Anzahl: </Text>
<AntDesign name="minussquareo" style={{marginRight: 6}} size={24} color="black" />
<TextInput onBlur={() => handleChange(1, product_id)} value={ isNaN(amount) ? '' : amount.toString() } onChangeText={e => handleChange(e, product_id)} style={{height: 28, width: 28, borderRadius: 4, textAlign: 'center', backgroundColor: '#eee'}} />
<AntDesign name="plussquareo" style={{marginLeft: 6}} size={24} color="black" />
</View>
</View>
</TouchableOpacity>
<View style={[styles.header, { marginTop: 4 }]}>
<ButtonWithoutLoader onPress={() => updateRecycler(prevState => !prevState)} title="Jetzt Kaufen!" width={width * 0.9} />
</View>
</TouchableWithoutFeedback>
);
});
return (
<FlatList
data={datas}
keyExtractor={item => item.item.product_id + Math.random(100)}
renderItem={({ item }) => <RenderItem item={item}/>}
contentContainerStyle={{justifyContent: 'center', alignItems: 'center'}}
removeClippedSubviews={true}
initialNumToRender={2}
maxToRenderPerBatch={1}
extraData={update}
updateCellsBatchingPeriod={100}
/>
);
};
........................................................................................................................................................................................
If you see the docs of RecyclerView, you will see for extendedState prop:
In some cases the data passed at row level may not contain all the info that the item depends upon, you can keep all other info outside and pass it down via this prop. Changing this object will cause everything to re-render. Make sure you don't change it often to ensure performance. Re-renders are heavy.
Based on your code you are updating this prop in button click and text change handler, this will eventually re-render your screen as per the description. So, here you would need to revise your logic to avoid unnecessary re-renders.
I recently just solved this problem in my own project so I'd be glad to help.
The main issue is that you can't have ANY UI related state in your list items. None. You must instead move all of that information to be transferred through props.
I see your only instance of that is through your TextInput. This could be difficult. So my first question would then be: do you really need RecyclerListView? Unless your list is thousands of items long, and items have a complicated/image intensive UI, I'd suggest FlatList for this project.
If you do continue to need RecyclerListView, I'd suggest making it so after a textinput is finished ('finished' as in maybe after a 3 second timer or, when they press 'submit' or something like that), you change the dataProvider's data object. Change the item at the index you need, and then resubmit it with cloneWithRows()

How can use useState() with Flatlist data?

I've had a problem when i used useState(). i have to filter by searched words on my data and list.
i need to define my data list with State (i'd list with searched words) but when i use State, i've taken 'Invalid Hook' error.
let [list, setList] = useState(data);
//called
data={list}
I don't find where i use that , I couldn't fix for 3 days, i can't reach next step :( I hope i'll fix with expert helps...
import React, {Component, useState} from 'react'
import {
Text,
StyleSheet,
View,
FlatList,
SafeAreaView,
ScrollView,
Image,
TextInput,
} from 'react-native'
import data from '../../data'
export default class Flatlistexample extends Component {
render () {
//defined below
let [list, setList] = useState(data);
seachFilter=(text)=>{
const newData = data.filter(item=>{
const listitem= `${item.name.toLowerCase()} ${item.company.toLowerCase()}`;
return listitem.indexOf(text.toLowerCase())
})
};
return (
<SafeAreaView
style={{
flex: 1,
}}>
<FlatList
//called
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}
ListHeaderComponent={() => {
const [search, setSearch] = useState('');
return (
<View style={styles.seachContainer}>
<TextInput
style={styles.textInput}
placeholder={'Search...'}
value={search}
onChangeText={text=>{
setSearch(text)
}}
></TextInput>
</View>
)
}}
/>
</SafeAreaView>
)
}
}
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,
},
})
Thank you
React hooks can be used with functional component only, here you are using class component
You need to understand the difference between functional component and class component first.
Here you are using class component so your state should be manageed in the following way
export default class Flatlistexample extends Component {
constructor(props)
{
this.state={list:[]}
}
}
and to update list
this.setState({list: <array of data>})
If you want to use hooks, your component needs to be changed something like the following:
const Flatlistexample = () => {
//defined below
let [list, setList] = useState(data);
seachFilter = (text) => {
const newData = data.filter(item => {
const listitem = `${item.name.toLowerCase()} ${item.company.toLowerCase()}`;
return listitem.indexOf(text.toLowerCase())
})
};
return (
<SafeAreaView
style={{
flex: 1,
}}>
<FlatList data={list} renderItem={Your flatlist Item}/>
</SafeAreaView>
)
}
export default Flatlistexample
Here you go, I've added lots of comments. I hope you find this instructive. Let me know if you have questions!
import React, { useMemo, useState } from 'react'
import {
Text,
StyleSheet,
View,
FlatList,
SafeAreaView,
ScrollView,
Image,
TextInput,
} from 'react-native'
import data from '../../data'
// changed this to a functional component so you can use hooks. You can't use hooks in class components.
const Flatlistexample = () => {
// you don't actually need to `useState` for your list, since you're always just filtering `data`
// you would need to use `useState` if you were receiving data from an API request, but here it's static
const [search, setSearch] = useState('') // this should live in the main component so you can filter the list
const parsedSearch = search.toLowerCase() // do this once outside the filter, otherwise you're converting it for each item in the data array
const filteredList = useMemo(
() =>
data.filter(item => {
const itemText = `${item.name.toLowerCase()} ${item.company.toLowerCase()}`
return itemText.indexOf(parsedSearch) > -1 // returns `true` if search is found in string
}),
[parsedSearch], // this will only run if parsedSearch changes
)
return (
<SafeAreaView style={{ flex: 1 }}>
<FlatList
//called
data={filteredList} // use the filtered list here
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}
ListHeaderComponent={() => {
return (
<View style={styles.seachContainer}>
<TextInput
style={styles.textInput}
placeholder={'Search...'}
value={search}
onChangeText={text => {
setSearch(text)
}}
/>
</View>
)
}}
/>
</SafeAreaView>
)
}
export default Flatlistexample

React Native, render a button if condition is true

I would like to know if there is an easy way to render dynamicly components into a view depending on a condition, like "userpermission='admin', which then shows more buttons that a user has without this var. something like this:
import React, { useState } from 'react';
import {Button, Text, View, StyleSheet, TouchableOpacity} from 'react-native';
const HomeScreen = ({ navigation }) => {
const userpermission = 'admin';
const adminbutton = '<Button title="Adminstuff"></Button>';
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Applikationen</Text>
<TouchableOpacity
style={styles.button}
onPress={() => navigation.navigate('Arbeitszeiterfassung')}>
<Text style={styles.text}>Arbeitszeiterfassung</Text>
</TouchableOpacity>
// HERE I WANT TO RENDER THE BUTTON
// if(userpermission == 'admin'){
// {adminbutton}
// }
</View>
);
};
You can do something like this.
import React, { useState } from 'react';
import {Button, Text, View, StyleSheet, TouchableOpacity} from 'react-native';
const HomeScreen = ({ navigation }) => {
const userpermission = 'admin';
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Applikationen</Text>
<TouchableOpacity
style={styles.button}
onPress={() => navigation.navigate('Arbeitszeiterfassung')}>
<Text style={styles.text}>Arbeitszeiterfassung</Text>
</TouchableOpacity>
{userpermission == "admin" ? <Button title="Adminstuff" /> : null}
</View>
);
};
Try this way
const HomeScreen = ({ navigation }) => {
const userpermission = 'admin';
const adminbutton = '<Button title="Adminstuff"></Button>';
const renderButtonsContainer = () => {
return <View>
<Button title="Adminstuff"></Button>
<Button title="Adminstuff"></Button>
.........
</View>
}
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
{userpermission == 'admin' ? renderButtonsContainer() : null }
</View>
);
};
A better way to achieve this in functional component.
import { Button } from 'react-native';
const MyButton = ({userpermission}) => {
if(userpermission == 'admin'){
return <Button title="Adminstuff"/>
}
else {
return <Button title="Userstuff"/>
}
}
const HomeScreen = () => {
const userpermission = 'admin';
return (
<View>
<View>Something</<View>
<MyButton userpermission={userpermission} />
</View>
)
}

TextInput loses focus after every keystroke react-native

I have the following code (full example):
import React, { useState, useEffect } from 'react';
import { SafeAreaView, View, TextInput, Button, StyleSheet } from 'react-native';
const App = () => {
const [textblocks, setTextblocks] = useState([]);
const CreateTextBlockHandler = () => {
let array = [...textblocks];
array.push({text: ''});
setTextblocks(array);
};
const SaveTextHandler = (index, text) => {
let array = [...textblocks];
array[index].text = text;
setTextblocks(array);
};
const RenderTextInputs = () => {
return textblocks.map((item, index) => {
return (
<View key={index}>
<TextInput style={styles.textinput} placeholder="text" value={textblocks[index].text} onChangeText={value => SaveTextHandler(index, value)} />
</View>
);
});
};
return (
<SafeAreaView style={styles.pancontainer}>
<RenderTextInputs />
<Button title="Create textblock" onPress={CreateTextBlockHandler} />
</SafeAreaView>
);
};
const styles = StyleSheet.create({
pancontainer: {
flex: 1,
alignItems: 'center',
justifyContent: 'center'
},
textinput: {
width: 200,
margin: 10,
borderWidth: 1,
borderColor: 'black'
}
});
export default App;
How it works: I have a button to dynamically add a new textinput. This works. The problem is, for every character I enter in a textput, the focus is lost after every character.
I created a snack, you can test it here: https://snack.expo.io/BJcHxluyI.
I THINK I need to save the reference to the textinput somewhere, and then give the focus back to the textinput after every keystroke, but I don't know how to do that.
Change
return (
<SafeAreaView style={styles.pancontainer}>
<RenderTextInputs />
<Button title="Create textblock" onPress={CreateTextBlockHandler} />
</SafeAreaView>
);
To
return (
<SafeAreaView style={styles.pancontainer}>
{RenderTextInputs()}
<Button title="Create textblock" onPress={CreateTextBlockHandler} />
</SafeAreaView>
);
Or put RenderTextInputs outside App and pass data via props. With first syntax react treats RenderTextInputs as a component and, as it is nested in App, mounts it again on each App render.