I have a component that is supposed to display a "cards" containing information saved in an array in state. I get this information from a JSON file and save it into my array in a "componentDidMount". I then made a function called "displayFood" before the return of my render function, which I then use in my render functions return. The problem is that when I run the code no cards are being displayed.
import React from 'react'
import "./style.scss";
import FoodData from "./foodData.json";
class Food extends React.Component {
constructor(props){
super(props);
this.state={
foodData: []
}
}
componentDidMount(){
FoodData.map((foodItem,index) => {
var foodTemp = {
id: index,
name: foodItem.name,
pic: foodItem.pic,
serving: foodItem.serving,
calories: foodItem.calories,
sugar: foodItem.sugar,
protien: foodItem.protien
}
this.setState((prevState) => {
prevState.foodData.push(foodTemp)
})
})
}
render() {
const displayFood = () => {
var i;
for(i = 0; i < this.state.foodData.length; i++){
return(
<div className="food-card">
<img src={require(`${this.state.foodData[i].pic}`)}/>
<ul>
<li>{this.state.foodData[i].name}</li>
<li>Serving: {this.state.foodData[i].serving}</li>
<li>Calories: {this.state.foodData[i].calories}</li>
<li>Sugar: {this.state.foodData[i].sugar}</li>
<li>Protien: {this.state.foodData[i].protien}</li>
</ul>
<button name={this.state.foodData[i].name}>Add</button>
</div>
)
}
}
return(
<div>
<div className="food-container">
{
displayFood()
}
</div>
</div>
)
}
}
export default Food;
Loading...
`. Because, in real App, the data will not come from JSON file but from API, `componentWillMount` cannot help you a that time. And from version 17, 'componentWillMount' will be deprecated https://reactjs.org/docs/react-component.html#unsafe_componentwillmount – bird Mar 21 '19 at 02:26