Вывад масіву аб'ектаў у React
Няхай у нас ёсць масіў аб'ектаў з прадуктамі:
const prods = [
{name: 'product1', cost: 100},
{name: 'product2', cost: 200},
{name: 'product3', cost: 300},
];
function App() {
}
Давайце выведзем кожны прадукт у сваім абзацы:
function App() {
const res = prods.map(function(item) {
return <p>{item.name} {item.cost}</p>;
});
return <div>
{res}
</div>;
}
Можна назву і цану прадукта пакласці ў асобны тэг, напрыклад, вось так:
function App() {
const res = prods.map(function(item) {
return <p>
<span>{item.name}</span>:
<span>{item.cost}</span>
</p>;
});
return <div>
{res}
</div>;
}
Не забудзем дадаць атрыбут key:
function App() {
const res = prods.map(function(item, index) {
return <p key={index}>
<span>{item.name}</span>:
<span>{item.cost}</span>
</p>;
});
return <div>
{res}
</div>;
}
У кампаненце App даны наступны масіў:
const users = [
{name: 'user1', surn: 'surn1', age: 30},
{name: 'user2', surn: 'surn2', age: 31},
{name: 'user3', surn: 'surn3', age: 32},
];
Выведзіце элементы гэтага масіву ў выглядзе спісу
ul.