I have a list of dictionaries set as props
in my React
component, like so:
JavaScript
x
2
1
console.log(fruits): [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…} ]
2
The dicts:
JavaScript
1
14
14
1
0:
2
name: 'Apple'
3
color: 'Red'
4
5
1:
6
name: 'Banana'
7
color: 'Yellow'
8
9
2:
10
name: 'Pear'
11
color: 'Green'
12
13
.
14
And I need to display their NAMES in the rows, each row based on a respective fruit color:
JavaScript
1
39
39
1
class Basket extends Component {
2
constructor(props) {
3
super(props);
4
5
this.state = {
6
fruits:[],
7
isLoaded:false
8
};
9
}
10
11
render() {
12
13
const { fruits } = this.props;
14
console.log(fruits)
15
16
return (
17
<div className="app">
18
<div className="fruit-wrapper">
19
<div className="row">
20
<Fruit>Apple</Fruit>
21
<Fruit>Red 2</Fruit>
22
<Fruit>Red 3</Fruit>
23
</div>
24
<div className="row">
25
<Fruit>Banana</Fruit>
26
<Fruit>Yellow 2</Fruit>
27
<Fruit>Yellow 3</Fruit>
28
</div>
29
<div className="row">
30
<Fruit>Pear</Fruit>
31
<Fruit>Green 1</Fruit>
32
<Fruit>Green 2</Fruit>
33
</div>
34
</div>
35
</div>
36
</div>
37
);
38
}
39
export default Basket;
How can I map fruit object values from this list os dicts and display fruit names assigning each name to its respective row color?
Advertisement
Answer
JavaScript
1
30
30
1
import React from "react";
2
3
function Fruit({ children }) {
4
return <div>{children}</div>;
5
}
6
7
export default class Basket extends React.Component {
8
state = {
9
isLoaded: false
10
};
11
12
render() {
13
const { fruits } = this.props;
14
15
return (
16
<div className="app">
17
<div className="fruit-wrapper">
18
{fruits.map(({ name, color }) => (
19
<div className="fruit-wrapper">
20
<Fruit>{name}</Fruit>
21
<Fruit>{color} 2</Fruit>
22
<Fruit>{color} 3</Fruit>
23
</div>
24
))}
25
</div>
26
</div>
27
);
28
}
29
}
30