Reputation: 1469
I'm attempting to render a table using ReactJS, but get an error -Cannot read property 'map' of undefined -
The code:
import React, { Component } from 'react';
import './Table.css'
const obj = [{
name: "onion",
price: ".99",
id: 1
}, {
name: "pepper",
price: "1.25",
id: 2
}, {
name: "broccoli",
price: "3.00",
id: 3
}];
class TableRow extends React.Component {
render() {
const {
data
} = this.props;
const row = data.map((data) =>
<tr>
<td key={data.name}>{data.name}</td>
<td key={data.id}>{data.id}</td>
<td key={data.price}>{data.price}</td>
</tr>
);
return (
<span>{row}</span>
);
}
}
class Table extends Component {
constructor(props) {
super(props)
}
render() {
return (
<table>
<TableRow data={this.props.data} />
</table>
);
}
}
export default Table;
I imported the table component into the App.js file. However, the error occurs on the following line of Table.js: const row = data.map((data) => ...could I get some assistance please?
Upvotes: 0
Views: 927
Reputation: 424
You are most likely not passing an array down into Table
as data
.
The Table component should be set in App.js or where you're using it like this:
class App extends Component {
render() {
return (
<div className="App">
<Table data={[1,5,6,etc. . .]} /> \\data has an array of whatever values you care for.
</div>
);
}
}
Afterwards you will also have another problem because you should not be setting data = this.props
in TableRow
. data
should be set to this.props.data
like so:
const {
data
} = this.props.data;
Upvotes: 0
Reputation: 12874
In your table
class, change the below code from <TableRow data={this.props.data} />
to <TableRow data={obj} />
.
You defined obj
but you never use it anywhere. When the program rendering your table
class, and trying to render TableRow
, it pass data using data
prop. But you're passing using this.props.data
where you don't have the data for it, and hence when TableRow
trying to apply map
function it hits exception
Upvotes: 2