I have a simple json with nested array:
{"pageIndex":1,"items":[{"id":1,"name":"name1"},{"id":2,"name":"name2"}],"hasPage":false}
I try to map items for the table rendering:
import React from 'react'
const TableBody = props => {
const rows = props.characterData.map((row, index) => {
return (
<tr key={index}>
<td>{row.id}</td>
<td>{row.name}</td>
</tr>
)
})
return <tbody>{rows}</tbody>
}
const Table = props => {
const { characterData } = props
return (
<table>
<TableBody characterData={characterData} />
</table>
)
}
export default Table
with
import React, { Component } from 'react'
import Table from './Table'
class App extends Component {
state = {
characters: [],
}
componentDidMount() {
const url =
'http://mysitename.com/api/characters'
fetch(url)
.then(result => result.json())
.then(result => {
this.setState({
characters: result,
})
})
}
render() {
const { characters } = this.state
return (
<div className="container">
<Table characterData={characters} />
</div>
);
}
}
export default App
But I give an error: TypeError: props.characterData.map is not a function, this code works only for not nested array in json.
When I change to this: const rows = props.characterData.items.map((row, index) => { I have an error TypeError: Cannot read property 'map' of undefined
I see in react console that characterData.items in TableBody have values. But why I can not map them? And why items are undefined?
{characters.length > 0 ? <Table characterData={characters} /> : null}maybe this will help