Reputation: 940
I am rendering a table from mapped elements stored in the React state. However, the tr row elements are not rendered in the tbody component, even though console commands show the data is there. The code to render table rows from this.state.tableData
is:
componentWillMount() {
let data = this.props.dbPersons.get("directory");
this.setState({ tableData: data });
}
...
renderTableData() {
return this.state.tableData.map((student, index) => {
const { id, person } = student;
console.log("id'", id);
console.log("person.lastName", person.lastName);
return (
<tr key={index}>
<td>{id}</td>
<td>{person.lastName}</td>
</tr>
)
})
}
tbody is rendered if tableData is stored in the state:
{this.state.tableData && <tbody>
{this.renderTableData()}
</tbody>}
But when the page is opened, the console displays the row data but tbody is rendered without any rows. Why? Does the component need to be refreshed somehow? Has the tbody component already been rendered and cannot be updated?
Upvotes: 0
Views: 395
Reputation: 1014
renderTableData() {
var data = this.state.tableData.map((student, index) => {
const { id, person } = student; console.log("id'", id);
console.log("person.lastName", person.lastName);
return (<tr key={index}>
<td>{id}</td>
<td>{person.lastName}</td>
</tr>)
})
return data;
}
Upvotes: -1
Reputation: 39320
Other than componentWillMount causing a warning (replace it with compontDidMount) there is nothing wrong with the code you posted so far. I don't see a reason why it would log but not render. Here is a working example of your code:
class App extends React.Component {
state = { tableData: false };
componentWillMount() {
setTimeout(
() =>
this.setState({
tableData: [{ id: 1 }, { id: 2 }],
}),
500
);
}
renderTableData() {
return this.state.tableData.map((student, index) => {
const { id } = student;
console.log('id', id);
return (
<tr key={index}>
<td>{id}</td>
{/* <td>{name}</td> removed this but still can see id*/}
</tr>
);
});
}
render() {
return (
<table>
{this.state.tableData && (
<tbody>{this.renderTableData()}</tbody>
)}
</table>
);
}
}
ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="root"></div>
Maybe you can provide a minim example that demonstrates the behavior you are experiencing.
Upvotes: 0