Reputation: 531
I am trying to map an array i.e static json data . Unable to map as I am getting error as this.props.movies.map is not a function. Below is the code for Table component with App.js. as the object in json file is movies.as I followed the same step on fetching api but was able to get data
import data from '../src/data.json'
class App extends Component {
constructor(props) {
super(props)
this.state = {
movies: data,
}
}
render() {
return (
<div className="App">
<Header />
<Table movies={this.state.movies} />
</div>
);
}
}
Table.js
import React, { Component } from 'react';
import './Table.css';
import { list } from 'postcss';
class Table extends Component {
constructor(props) {
super(props);
this.state = { }
}
render() {
const list = this.props.movies.map((movie) => (
<tr key={movie.Title}>
<td>{movie.Title}</td>
<td>{movie.Director}</td>
</tr>
)
);
return (
<div className="table">
table
<table>
<thead>
<tr>
<th>Title</th>
<th>Director</th>
</tr>
</thead>
<tbody>
{list}
</tbody>
</table>
</div>
);
}
}
export default Table;
Upvotes: 1
Views: 69
Reputation: 33974
The issue is your data contains movies array. So you need to assign data.movies to movies when you are initializing the state. Check below one for better understanding
class App extends Component {
constructor(props) {
super(props)
this.state = {
movies: data.movies,
}
}
render() {
const { movies } = this.state;
return (
<div className="App">
<Header />
{movies.length === 0 ? <h1>Loading Movies</h1> : <Table movies={this.state.movies} />}
</div>
);
}
}
Upvotes: 1