How to load and map data in reactjs material Table. I'm passing an object to child component via Cards
component. when console log I can receive object from parent but it is throwing failed to compile
error. Can anyone let me know where I made mistake?
Card.tsx
function createData(type: any, description: any, volume: any) {
return { type, description, volume };
}
class Card extends Component {
constructor(props: any) {
super(props);
const rows = props.value.cargo;
rows.map((data: any) => {
createData(data.type, data.description, data.volume);
});
}
render() {
return (
<Card className="Card">
<CardContent className="Card-Content">
<Table className="Card-Content__Table">
<TableHead>
<TableRow>
<TableCell>type</TableCell>
<TableCell>description</TableCell>
<TableCell>volume</TableCell>
</TableRow>
</TableHead>
<TableBody>
{rows.map(row => (
<TableRow key={row.volume}>
<TableCell component="th" scope="row">
{row.type}
</TableCell>
<TableCell>{row.description}</TableCell>
<TableCell>{row.volume}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</CardContent>
</Card>
);
}
}
Cards.tsx
render() {
return (
<div>
{this.state.card.map((card: any) => (
<Card key={card.id} value={card} />
))}
</div>
);
}
The const rows
you defined in the constructor isn't accessible from render()
. It is only accessible within the constructor function. If you wanted to create a parameter that would be accessible within the whole class, you could create it like this:
this.rows = props.value.cargo;
And then access it using this.rows
instead of just rows
.
For this example, though, that serves no purpose and would give you other problems in the future with the props not updating correctly between renders.
You should use this.props.value.cargo.map
instead of rows.map
in render()
. You can also create another const rows
inside of render()
, if you wanna make it cleaner. It's OK that they both have the same name, since they are in different scopes.