I am trying to make the FlatList component show the data from students objects array. Here's my current code.
import { Text, View, StyleSheet, TextInput, TouchableOpacity, FlatList } from 'react-native';
import {useState} from 'react';
export default function App() {
const [name, setName] = useState("");
const [age, setAge] = useState(0);
const [gender, setGender] = useState("");
const [students, setStudents] = useState([]);
const submit = () => {
setStudents(students [
{
id: Math.floor(Math.random * 100000),
name: name,
age: age,
gender: gender
}
]);
}
return (
<View>
<Text style={styles.title}>Students List</Text>
<Text style={styles.fieldNames}>Name</Text>
<TextInput placeholder="Enter name here..." style={styles.inputField} onChangeText={(name) => setName(name)}></TextInput>
<Text style={styles.fieldNames}>Age</Text>
<TextInput placeholder="Enter age here..." style={styles.inputField} onChangeText={(age) => setAge(age)}></TextInput>
<Text style={styles.fieldNames}>Gender</Text>
<TextInput placeholder="Enter gender here..." style={styles.inputField} onChangeText={(gender) => setGender(gender)}></TextInput>
<TouchableOpacity style={styles.buttons} onPress={submit}>
<Text style={{color: 'white'}}>Submit</Text>
</TouchableOpacity>
<TouchableOpacity style={styles.buttons}>
<Text style={{color: 'white'}}>Reset</Text>
</TouchableOpacity>
<FlatList
data={students}
renderItem={({item}) => {
<Text style={{color: 'black'}}>{item.name} {item.age} {item.gender}</Text>
}}
/>
</View>
);
}
const styles = StyleSheet.create({
title: {
fontSize: 20,
textAlign: 'center',
marginTop: 20,
fontWeight: 500
},
inputField: {
borderWidth: 2,
padding: 5,
marginLeft: 20,
marginRight: 20
},
fieldNames: {
marginLeft: 20,
marginTop: 20,
marginBottom: 5,
},
buttons: {
backgroundColor: 'blue',
paddingTop: 10,
paddingBottom: 10,
textAlign: 'center',
marginTop: 20,
marginLeft: 20,
marginRight: 20,
}
});
And here's the screenshot of the app till now.
I have no clue what's going wrong and have failed to find a solution online. Can someone please help? Thank you.
I want the FlatList to display the data from the students objects array.
CodePudding user response:
' ' is a concatenation operator in js. [] {} will not result in the object getting added as an element to the array.
Try doing this instead:
setStudents([...students,
{
id: Math.floor(Math.random * 100000),
name: name,
age: age,
gender: gender
}
]);
CodePudding user response:
studends array should be like this
setStudents([...students,
{
id: Math.floor(Math.random * 100000),
name: name,
age: age,
gender: gender
}
]