How to print multiple datas in FlatList - reactjs

export default class App extends Component {
constructor() {
super();
// flatlist data
this.state = {
data: [
{ key: "Skptricks", data: "one", name: "one" },
{ key: "Sumit" , data: "two" , name: "one"},
{ key: "Amit" , data: "three", name: "one"},
],
}
}
// flat list
render() {
return (
<View>
<FlatList
data={this.state.data}
renderItem={({item}) => <Text>{item.name}</Text>
/>
</View>
);
}
}

Can you explain what exactly do you need to print ? Please refer the code. I'm printing the 'name' item of your array. If you want to print 'data' items , use item.data inside renderItem. Let me know if you need any help.
const DATA = [{ key: "Skptricks", data: "one", name: "one" },
{ key: "Sumit" , data: "two" , name: "one"},
{ key: "Amit" , data: "three", name: "one"},
];
const Item = ({ name }) => (
<View style={styles.item}>
<Text style={styles.name}>{name}</Text>
</View>
);
const App = () => {
const renderItem = ({ item }) => (
<Item name={item.name} />
);
return (
<SafeAreaView style={styles.container}>
<FlatList
data={DATA}
renderItem={renderItem}
keyExtractor={item => item.id}
/>
</SafeAreaView>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
marginTop: StatusBar.currentHeight || 0,
},
item: {
backgroundColor: '#f9c2ff',
padding: 20,
marginVertical: 8,
marginHorizontal: 16,
},
name: {
fontSize: 32,
},
});

Related

How to select and deselect multiple item in react-native using Hooks with nested array

I'm trying to update state inside a nested array with a map function and spread operator, but i don't understand how to get the key in the key/value pair to select a nested object .
In below code, when i try to implement multiple selection but i acheive only single selection in innerarray1 and how to update innerarray1 with original data using state, i try .. but not work can any one pls help how to multiselection data ?
I want multiple time circle selected when i click see below image it might have an idea i try to implement
see below code , but i am stuck at a point , please help?
enter image description here
const [Data, setData] = useState([
{
id: 0,
title: ' Cycling',
Days: '3 Days completed',
innerArray: [
{
id: 1,
name: 'MON',
image: require('../../../../assets/Images/rightWhite.png'),
isselected: false,
},
{
id: 2,
name: 'TUE',
image: require('../../../../assets/Images/rightWhite.png'),
isselected: false,
},
{
id: 3,
name: 'WED',
image: require('../../../../assets/Images/rightWhite.png'),
isselected: false,
},
{
id: 4,
name: 'THU',
image: require('../../../../assets/Images/rightWhite.png'),
isselected: false,
},
{
id: 5,
name: 'FRI',
image: require('../../../../assets/Images/rightWhite.png'),
isselected: false,
},
{
id: 6,
name: 'SAT',
image: require('../../../../assets/Images/rightWhite.png'),
isselected: false,
},
{
id: 7,
name: 'SUN',
image: require('../../../../assets/Images/rightWhite.png'),
isselected: false,
},
],
},
{
id: 1,
title: ' Bath',
Days: '4 days compelted',
innerArray: [],
},
]);
const onClick = (innerData, item) => {
//i am stuck in this section
let data1 = Data.map((val) => {
if (val.id == item.id) {
let innerarray1 = val.innerArray.map((value) => {
// console.log("innervalue is====>",value)
if (value.id == innerData.id) {
return { ...value, isselected: !value.isselected };
} else {
return { ...value };
}
});
// console.log("inner arrayData is====", innerarray1);
} else {
return { val };
}
});
};
<View>
<FlatList
data={Data}
style={{ marginBottom: 200 }}
renderItem={({ item }) => (
<View>
<View style={{ height: hp('2%') }}></View>
<View
style={{
height: hp('17%'),
width: wp('80%'),
}}
>
<View
style={{
height: hp('5%'),
width: wp('70%'),
flexDirection: 'row',
alignSelf: 'center',
}}
>
<View
style={{
height: hp('5%'),
width: wp('30%'),
justifyContent: 'center',
}}
>
<Text>{item.title}</Text>
</View>
<View
style={{
height: hp('5%'),
width: wp('40%'),
justifyContent: 'center',
}}
>
<Text>{item.Days}</Text>
</View>
</View>
<FlatList
data={item.innerArray}
horizontal={true}
showsHorizontalScrollIndicator={false}
showsVerticalScrollIndicator={false}
style={{ marginTop: 10, marginLeft: wp('2%') }}
renderItem={({ item: innerData, index }) => (
// {selectedData(innerData)}
<View
style={{
height: hp('10%'),
justifyContent: 'space-between',
width: wp('12%'),
}}
>
<View style={{ height: hp('4%') }}>
<Text>{innerData.name}</Text>
</View>
<TouchableOpacity
style={styles.circleView1}
onPress={() => {
// onSelect(innerData , item)
onClick(innerData, item);
}}
>
<Text></Text>
</TouchableOpacity>
</View>
)}
/>
</View>
</View>
)}
/>
</View>;
I'm trying to update state inside a nested array with a map function and spread operator, but i don't understand how to get the key in the key/value pair to select a nested object .
you can update your state like this
[1]: https://i.stack.imgur.com/q0lh6.png
You have to just change your onClick function like below, with that you can achieve multiple selection
const onClick = (innerData, item) => {
console.log('innerData ', innerData);
console.log('item ', item);
let data1 = Data.map((val) => {
if (val.id == item.id) {
let innerarray1 = val.innerArray.map((value) => {
// console.log("innervalue is====\>",value)
if (value.id == innerData.id) {
return { ...value, isselected: !value.isselected };
} else {
return { ...value };
}
});
let totalSelected = innerarray1.filter(
(item) => item.isselected === true
).length;
console.log('inner arrayData is====', innerarray1);
return {
...val,
innerArray: innerarray1,
Days: `${totalSelected.toString()} Days completed`,
};
} else {
return { val };
}
});
console.log('Data1 is====', data1);
setData(data1);
};

Get data from an array to create dynamically <Text> component react-native

I got array:
const DATA_Section = [
{
id: 0,
text: "Some text1",
},
{
id: 1,
text: "Some text2",
},
{
id: 2,
text: "Some text 3",
},
];
and I want to use text from this array to create dynamic component. Idea is: I can see text[0], I click some button then I can see text[1], something like loop. How can to do it?
You can do this way maybe.
const DATA_Section = [
{
id: 0,
text: "Some text1",
},
{
id: 1,
text: "Some text2",
},
{
id: 2,
text: "Some text 3",
},
];
const Component: FC = () => {
const [initialRenderState, setInitialRenderState] =
useState(DATA_Section[0])
return (
<View>
{intialRenderState.map(item => <Text key={item.id}>{item.text}</Text>)}
<Pressable onPress={()=> setInitialRenderState(prevState => [...prevState, Data_Section[prevState.length]])}>
<Text>Add item</Text>
<Pressable>
</View>
)
}
const DATA_Section = [
{
id: 0,
text: "Some text1",
},
{
id: 1,
text: "Some text2",
},
{
id: 2,
text: "Some text 3",
},
];
const sample = () => {
const [ index, setIndex ] = useState(0);
const handleChangeIndex = () => {
if (index < DATA_Section.length) {
setIndex(index + 1);
}else{
setIndex(0);
}
}
return(
<View style={{flex:1}}>
<TouchableWithoutFeedback onPress={()=>handleChangeIndex()}>
<View style={{width:100, height:50, backgroundColor:'red'}}>
<Text>
{DATA_Section[index].text}
</Text>
</View>
</TouchableWithoutFeedback>
</View>
);
}

Why does my FlatList not scroll in React Native?

I have seen a lot of answers for FlatList not scrolling for React Native, but none of the answers seem to work.
The answer usually says to add flex: 1 to the parent, but here is an example that has that and it still doesn't scroll.
You can test here, but make sure you select iOS or Android. It does scroll for web.
import React from 'react';
import { SafeAreaView, View, FlatList, StyleSheet, Text, StatusBar } from 'react-native';
const DATA = [
{
id: "bd7acbea-c1b1-46c2-aed5-3ad53abb28ba",
title: "First Item",
},
{
id: "3ac68afc-c605-48d3-a4f8-fbd91aa97f63",
title: "Second Item",
},
{
id: "58694a0f-3da1-471f-bd96-145571e29d72",
title: "Third Item",
},
{
id: "58694a0f-3da1-471f-bd96-145571e29d73",
title: "Fourth Item",
},
{
id: "58694a0f-3da1-471f-bd96-145571e29d74",
title: "Fifth Item",
},
{
id: "58694a0f-3da1-471f-bd96-145571e29d75",
title: "Sixth Item",
},
{
id: "58694a0f-3da1-471f-bd96-145571e29d76",
title: "Seventh Item",
},
{
id: "58694a0f-3da1-471f-bd96-145571e29d77",
title: "Eighth Item",
},
{
id: "58694a0f-3da1-471f-bd96-145571e29d77",
title: "Ninth Item",
},
{
id: "58694a0f-3da1-471f-bd96-145571e29d77",
title: "Tenth Item",
},
];
const Item = ({ title }) => (
<View style={styles.item}>
<Text style={styles.title}>{title}</Text>
</View>
);
const App = () => {
const renderItem = ({ item }) => (
<Item title={item.title} />
);
return (
<SafeAreaView style={styles.container}>
<FlatList
data={DATA}
renderItem={renderItem}
keyExtractor={item => item.id}
/>
</SafeAreaView>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
marginTop: StatusBar.currentHeight || 0,
},
item: {
backgroundColor: '#f9c2ff',
padding: 20,
marginVertical: 8,
marginHorizontal: 16,
},
title: {
fontSize: 32,
},
});
export default App;
Modify the SafeAreaView to be within it's own container and added a View container with flexGrow: 1 instead of flex: 1:
const App = () => {
return (
<SafeAreaView style={styles.safe}>
<View style={styles.container}>
<FlatList
data={data}
renderItem={({ item }) => (<Item title={item.title} />) }
keyExtractor={item => item.id}
/>
</View>
</SafeAreaView>
);
}
const styles = StyleSheet.create({
safe: {
marginTop: StatusBar.currentHeight || 0,
},
container: {
flexGrow: 1
},
item: {
backgroundColor: '#f9c2ff',
padding: 20,
marginVertical: 8,
marginHorizontal: 16,
},
title: {
fontSize: 32,
},
});
Above worked in a snack Expo testing for iOS. Entire sample code with a little re-write:
import React from 'react';
import { SafeAreaView, View, FlatList, StyleSheet, Text, StatusBar } from 'react-native';
const data = [
{
id: "bd7acbea-c1b1-46c2-aed5-3ad53abb28ba",
title: "First Item",
},
{
id: "3ac68afc-c605-48d3-a4f8-fbd91aa97f63",
title: "Second Item",
},
{
id: "58694a0f-3da1-471f-bd96-145571e29d72",
title: "Third Item",
},
{
id: "58694a0f-3da1-471f-bd96-145571e29d73",
title: "Fourth Item",
},
{
id: "58694a0f-3da1-471f-bd96-145571e29d74",
title: "Fifth Item",
},
{
id: "58694a0f-3da1-471f-bd96-145571e29d75",
title: "Sixth Item",
},
{
id: "58694a0f-3da1-471f-bd96-145571e29d76",
title: "Seventh Item",
},
{
id: "58694a0f-3da1-471f-bd96-145571e29d77",
title: "Eighth Item",
},
{
id: "58694a0f-3da1-471f-bd96-145571e29d77",
title: "Ninth Item",
},
{
id: "58694a0f-3da1-471f-bd96-145571e29d77",
title: "Tenth Item",
},
];
const Item = ({ title }) => (
<View style={styles.item}>
<Text style={styles.title}>{title}</Text>
</View>
);
const App = () => {
return (
<SafeAreaView style={styles.safe}>
<View style={styles.container}>
<FlatList
data={data}
renderItem={({ item }) => (<Item title={item.title} />) }
keyExtractor={item => item.id}
/>
</View>
</SafeAreaView>
);
}
const styles = StyleSheet.create({
safe: {
marginTop: StatusBar.currentHeight || 0,
},
container: {
flexGrow: 1
},
item: {
backgroundColor: '#f9c2ff',
padding: 20,
marginVertical: 8,
marginHorizontal: 16,
},
title: {
fontSize: 32,
},
});
export default App

FlatList doesn't render with React Hooks

I am trying to rename [0]items in FlatList by clicking some item, But it doesn't work for me, when i click on each item nothing happen and i don't get any error. How can i fix this?
This is my code.
export default function renameSample() {
const data = [
{
id: '1',
name: 'test1',
},
{
id: '2',
name: 'test2',
},
{
id: '3',
name: 'test3',
},
];
const [stateUser, onChangeUser] = useState(data);
return (
<FlatList
data={stateUser}
renderItem={({item}) =>
<TouchableOpacity
onPress={() => {
let setData = stateUser;
setData[0].name = 'changed';
onChangeUser(setData);
}
}
>
<Item name={item.name} />
</TouchableOpacity>
}
keyExtractor={item => item.id}
/>
</View>
);
}
If your requirement is to change the clicked item, the code would be like below.
You can get the index of the clicked item and change it.
function RenameSample() {
const data = [
{
id: '1',
name: 'test1',
},
{
id: '2',
name: 'test2',
},
{
id: '3',
name: 'test3',
},
];
const [stateUser, onChangeUser] = useState(data);
return (
<View>
<FlatList
data={stateUser}
renderItem={({ item, index }) => (
<TouchableOpacity
onPress={() => {
const newData=[...stateUser];
newData[index].name = 'changed';
onChangeUser(newData);
}}>
<Item name={item.name} />
</TouchableOpacity>
)}
keyExtractor={(item) => item.id}
/>
</View>
);
}

React Native Mapping through Array of Objects gives blank values

I'm trying to loop over a simple array of objects and display the content inside Text tag. The looping is being done but the actual content is not displayed on the screen.
import React from 'react';
import { StyleSheet, Text, View, Button } from 'react-native';
export default class App extends React.Component {
render() {
const initialArr = [
{
id: 1,
color: "blue",
text: "text1"
},
{
id: 2,
color: "red",
text: "text2"
},
{
id: 3,
color: "green",
text: "text3"
}
];
return (
<View style={styles.container}>
{initialArr.map((prop, key) => {
return (
<Text key={key}>{prop[1]}</Text>
);
})}
</View>
);
}
}
render() {
const initialArr = [
{ id: 1, color: "blue", text: "text1" },
{ id: 2, color: "red", text: "text2" },
{ id: 3, color: "green", text: "text3"}
];
var textInputComponents = initialArr.map((prop, key) => {
return (
<Text key={key}>{prop.text}</Text>
);
})
return (
<View style={styles.container}>
{textInputComponents}
</View>
);
}
Apart from John_mc's answer, instead of using inline mapping, you can also split the mapping operation, to improve readability and maintainability

Resources