I have arrays I'm passing via props like this:
{
id: 1,
Name: "Abe",
HitPointValue: "124",
StrengthValue: "12",
IntelligenceValue: "14",
WisdomValue: "16",
DexterityValue: "12",
ConstitutionValue: "10",
CharismaValue: "17",
Avatar: require('./images/avatar_1.jpg')
}
I receive these in a component like this:
static navigationOptions = ({ navigation }) => {
const {char} = state.params;
}
When I write out the properties of the array one by one like this, it works:
render() {
const { params } = this.props.navigation.state;
return (
<View>
<Text>
Name: {params.char.Name}{"\n"}
</Text>
</View>
)
}
But when I try to use "map" to loop through the array(like below), I just get an error that states "
undefined is not a function (params.char.map)
.
render() {
const { params } = this.props.navigation.state;
return (
<View>
{params.char.map(c =>
<Text>
{c.key} : {c.value} {"\n"}
</Text>
)}
</View>
)
}
I'm trying to follow this guide, Lists and Keys but it's not working.
What could I be doing wrong?
thanks!
Because that data is not an array, and map only works with array. Use Object.entries first then use map.
Write it like this:
render() {
const { params } = this.props.navigation.state;
return (
<View>
{Object.entries(params.char).map(([key,value], index) =>
<Text key={key}>
{key} : {value} {"\n"}
</Text>
)}
</View>
)
}
Check this snippet:
let obj = {
id: 1,
Name: "Abe",
HitPointValue: "124",
StrengthValue: "12",
IntelligenceValue: "14",
WisdomValue: "16",
DexterityValue: "12",
ConstitutionValue: "10",
CharismaValue: "17",
};
Object.entries(obj).map(([key, value], index) => console.log(key, value, index))
Related
I get an array after console log my state that get data from Firebase. I want to know: can anyone help me to map array and get below details on ui. Thank You.
I tried below way, but app keep getting errors
Array [
Object {
"lists": Array [
Object {
"lists": Array [
Object {
"id": "123",
"imageUrl": "http://www.pngmart.com/files/1/Pizza-Slice-PNG-Transparent-Image.png",
"name": "Chicken Devill pizza",
"price": 700,
"size": "Medium",
},
],
"randomid": "32013408-0f48-4b15-80c4-eba3fc1fe295",
},
Object {
"lists": Array [
Object {
"id": "1234",
"imageUrl": "http://www.pngmart.com/files/1/Cheese-Pizza.png",
"name": "Cheese pork pizza",
"price": 1500,
"size": "Medium",
},
],
"randomid": "12a74805-4932-4397-b838-6773bc7e44b8",
},
],
},
]
In below code it show a error:
TypeError: undefined is not a function (near '...this.state.lists.map...')
{this.state.lists.lists.map((current, i) => (
))}
The first list here is an array not an Object. You can't call lists.lists because of this.
You will need to flatten the list or use nested map operations.
export default function App() {
const state = {
lists: [
{
lists: [
{
id: "123",
imageUrl:
"http://www.pngmart.com/files/1/Pizza-Slice-PNG-Transparent-Image.png",
name: "Chicken Devill pizza",
price: 700,
size: "Medium"
}
],
randomid: "32013408-0f48-4b15-80c4-eba3fc1fe295"
},
{
lists: [
{
id: "1234",
imageUrl: "http://www.pngmart.com/files/1/Cheese-Pizza.png",
name: "Cheese pork pizza",
price: 1500,
size: "Medium"
}
],
randomid: "12a74805-4932-4397-b838-6773bc7e44b8"
}
]
};
return (
<div className="App">
{state.lists.map((list) => {
return list.lists.map((item) => {
return <p>{item.id}</p>;
});
})}
</div>
);
}
You can find this working here: https://codesandbox.io/s/nervous-tu-u2h8v?file=/src/App.js
I also want to add some thing by myself
I done the mapping inside a mapping like this
{this.state.lists.map((current, i) => (
<View>
{current.map((current, i) => (
<Fragment>
<TouchableOpacity style={styles.card} onPress={() => this.details(current.id)}>
<Image style={styles.img} key={i} source={{uri: current.lists[0].imageUrl}}/>
<Text style={styles.txt} key={i}>{current.lists[0].name}</Text>
<Text style={styles.txt} key={i}>{current.lists[0].size}</Text>
<Text style={styles.txt} key={i}>LKR.{current.lists[0].price}</Text>
</TouchableOpacity>
</Fragment>
))}
</View>
))}
I have an array:
[
{
"room": {
"id": "1",
"name": "NameRoom"
},
"users": [
{
"userId": "1",
"userName": "User1",
},
{
"userId": "2",
"userName": "User12",
},
{
"userId": "3",
"userName": "User13",
}
]
},
{
"room": {
"id": "2",
"name": "NameRoom2"
},
"users": [
{
"userId": "4",
"userName": "User14",
},
{
"userId": "5",
"userName": "User15",
},
{
"userId": "6",
"userName": "User16",
}
]
},
]
Here is my rendering code
componentDidMount() {
fetch('https://site.ru/api/rooms')
.then((response) => response.json())
.then((responseJson) => {
this.setState({
dataSource: responseJson,
})
console.log(responseJson[0].users[0].userName) // i get User1
})
.catch((error) => {
console.log(error)
})
}
renderItemRooms = ({ item,index }) => (
<View style = {styles.containerHeader}>
<Text style = {styles.dateTitle}>16.04.2020</Text>
</View>
<TouchableOpacity style = {styles.containerMain}>
<Text style = {styles.nameTitle}>RoomName</Text>
<IconButton
style={styles.menuIcon}
icon="text"
color={'#e7eee6'}
size={40}
onPress={this._toggleBottomNavigationView}
/>
<BottomSheet
visible={this.state.visible}
onBackButtonPress={this._toggleBottomNavigationView}
onBackdropPress={this._toggleBottomNavigationView}
>
<View style={styles.bottomNavigationView}>
<View style={styles.bottomList}>
<FlatList
keyExtractor={item => item.name}
data={this.state.dataSource}
renderItem={this.renderItemUsers}
/>
</View>
<View style={styles.bottomButton}>
<TouchableOpacity style={styles.buttonStyle}>
<Text>Connect</Text>
</TouchableOpacity>
</View>
</View>
</BottomSheet>
</TouchableOpacity>
)
How can I display a list of users in the internal render in my code?
And print the names of rooms.
How to iterate through such an array correctly?
I need to output TouchableOpacity with the name of the room, it has a button on the right, when you click it, a modal menu appears, which contains a list of users in this room, how do I do this correctly?
I've already searched the Internet and didn't find a similar problem.
I notice that you have missed something in FlatList, also there many methods to iterate an array. I will give you an example here and hope this helps.
Example:
<FlatList
keyExtractor={item => item.room.name} {/* item.name is undefined, you need to add room.name */}
data={this.state.dataSource}
renderItem={this.renderItemUsers}
/>
// And renderItemUsers method
renderItemUsers = ({ item }) => {
const Users = () => item.users.map(user => <Text key={user.userId}>{user.userName}</Text>)
return (
<View>
<Text>Room : {item.room.name}</Text>
<Users />
</View>
)
}
I have an array of Athletes objects that contain another array of teams objects that particular athlete has played for:
var athletes = [
{
"athlete_id": 123,
"first_name": "john",
"last_name": "doe",
"teams": [
{ "team_id": 4,"team_name": "Eagles" },
{ "team_id": 7, "team_name": "Knights" }
]
},
{
"athlete_id": 276,
"first_name": "jane",
"last_name": "doe",
"teams": [
{ "team_id": 4,"team_name": "Pilots" },
{ "team_id": 7, "team_name": "Thunder" }
]
}
];
I want to, very simply, render the items in this format (teams listed under full name):
John Doe
Eagles
Knights
Jane Doe
Pilots
Thunder
I have tried the following in the render()method:
<View>
{ athletes.map((item, key) => {
return <Text key={key}>{item.first_name} + " " + {item.last_name}</Text>
{ item.teams.map((unit, key2) => {
return <Text key={key2}>{unit.team_name}</Text>
})}
})}
</View>
With the above snippet of code, I have only been able to render the full names of both athletes, and not their teams. What can I do to achieve the proper output?
It is because you are returning the item with the first name, last name in it, before your code has chance to return any of the team data:
<View>
{ athletes.map((item, key) => {
return (
<View key={key}>
<Text>{item.first_name} {item.last_name}</Text>
{ item.teams.map((unit, key2) => {
return <Text key={key2}>{unit.team_name}</Text>
})}
</View>
);
})}
</View>
I am trying to display this JSON data:
[
{
"id":"1",
"imagename":"dog"
},
{
"id":"2",
"imagename":"cat"
},
{
"id":"3",
"imagename":"mouse"
},
{
"id":"4",
"imagename":"deer"
},
{
"id":"5",
"imagename":"shark"
},
{
"id":"6",
"imagename":"ant"
}
]
Here is the current code that I have to display that data:
componentDidMount(){
fetch(`http://www.example.com/React/data.php`, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
}).then((response) => response.json())
.then((responseJson) => {
this.data = responseJson;
this.setState({ loading: false });
}).catch((error) => {
console.warn(error);
});
}
return(
<View style = { styles.MainContainer }>
<View>
<Card>
<View>
<Text>{this.data.id}</Text>
<Text>{this.data.imagename}</Text>
</View>
</Card>
</View>
</View>
);
My result is that nothing displays, but when I just have this.data I get the object with keys error again.
Looking up similar answers to find my problem, I then attempted to .map, but I kept getting cannot not find variable: i:
this.data = responseJson.map(item => ({ ...item, i }))
And lastly here is the rest of my code for the attempt:
return(
<View style = { styles.MainContainer }>
<View>
<Card>
<View key={i}>
<Text>{item.id}</Text>
<Text>{item.imagename}</Text>
</View>
</Card>
</View>
</View>
);
When I put my json data into an array, nothing displays because (I'm guessing) there are no commas between the keys. Like this:
{"id":"1","imagename":"dog"}{"id":"2","imagename":"cat"}{"id":"3","imagename":"mouse"}{"id":"4","imagename":"deer"}{"id":"5","imagename":"shark"}{"id":"6","imagename":"ant"}
And if anyone needs to see my data.php:
Echos Object
$dsql = "SELECT * FROM random";
$dresult = $con->query($dsql);
if ($dresult->num_rows >0) {
while($drow[] = $dresult->fetch_assoc()) {
$dtem = $drow;
$djson = json_encode($dtem);
}
} else {
}
echo $djson;
Echos Array
$dsql = "SELECT * FROM random";
$dresult = $con->query($dsql);
if ($dresult->num_rows >0) {
while($drow = $dresult->fetch_assoc()) {
$dtem = $drow;
$djson = json_encode($dtem);
echo $djson;
}
} else {
}
I can see an error on the way you pass the argument i on your map function, please take a look to this simple example of how to use map to render <li> elements.
var dataSample = [
{ "id": "1", "imagename": "dog" },
{ "id": "2", "imagename": "cat" },
{ "id": "3", "imagename": "mouse" },
{ "id": "4", "imagename": "deer" },
{ "id": "5", "imagename": "shark" },
{ "id": "6", "imagename": "ant" }
];
const App = () => (
<div>
<ul>
{dataSample.map((data, i) => {
return <li key={i}>{i + ' - ' + data.imagename}</li>
})}
</ul>
</div>
);
ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
Is there a way to loop inside the render's return method?
I have an object that looks like this:
export var Characters = [
{
id: 1,
Name: "Abe",
HitPointValue: "124",
StrengthValue: "12",
IntelligenceValue: "14",
WisdomValue: "16",
DexterityValue: "12",
ConstitutionValue: "10",
CharismaValue: "17",
Avatar: require('./images/avatar_1.jpg')
},
{
id: 2,
Name: "Jake",
HitPointValue: "141",
StrengthValue: "21",
IntelligenceValue: "6",
WisdomValue: "5",
DexterityValue: "8",
ConstitutionValue: "20",
CharismaValue: "10",
Avatar: require('./images/avatar_2.jpg')
}
]
Instead of writing out each character in the object like this:
render() {
return (
<View>
<View>
<Image source={getAvatar(1)} />
</View>
<View>
<Text>
Name: { getName(1)
</Text>
</View>
</View>
)
}
I was wondering if I could just loop through it?
thanks!
Use the Array's map() method
e.g.
render() {
return (
<View>
{Characters.map(character =>
<View>
<Image source={character.avatar}/>
<Text>Name: {character.name}</Text>
</View>
)}
</View>
)
}