I want to loop over this array of objects to render them in a component in react, why the mapping is not working?
fruits:[{"value":"Apple","status":"Green"},{"value":"Orange ","status":"Yellow"},{"value":"Banana","status":"Green"}]
export interface FruitsStatus {
fruits: Record<string, string>;
}
const Fruits: (props: FruitsStatus) => JSX.Element = props => {
return (
{props.fruits.map((fruit, index) => {
return (
<tr key={index}>
<td>
{fruit.value}
</td>
<td > {fruit.status} </td>
</tr>
);
})}
)
}
CodePudding user response:
I think this is because there is no root tag to contain all tr tags
simply wrap it with fragment :
return (
<>
{props.fruits.map((fruit, index) => {
return (
<tr key={index}>
<td>
{fruit.value}
</td>
<td > {fruit.status} </td>
</tr>
);
})}
</>
)
CodePudding user response:
export interface FruitsStatus {
fruits: Record<string, string>[];
}
const Fruits: (props: FruitsStatus) => JSX.Element = props => {
return (
{props.fruits.map((fruit, index) => {
return (
<tr key={index}>
<td>
{fruit.value}
</td>
<td > {fruit.status} </td>
</tr>
);
})}
)
}
FruitStatus.fruits have to be an array instead of a single record.