this my code , how to just return the only searched items on this meals[] array?
constructor(props) {
super(props);
this.state = {
meals: [],
};
this.searchMeal = this.searchMeal.bind(this);
}
this my search function but i don't know how to make it's work!
searchMeal(event) {
let search = event.target.value;
let meals = this.state.mealsList;
let mealsContent = [];
if (search.length > 0) {
// searched meals
} else {
// get meals if no results
}
this.setState({
meals: mealsContent
});
}
CodePudding user response:
for example, you can use this code in your array
meals.map((meal, index) => {
if (meal.name.toLowerCase().includes(search.toLowerCase())) {
mealsContent.push(meal);
}
});
the final example is :
searchMeal(event) {
let search = event.target.value;
let meals = this.state.mealsList;
let mealsContent = [];
if (search.length > 0) {
// searched meals
meals.map((meal, index) => {
if (meal.name.toLowerCase().includes(search.toLowerCase())) {
mealsContent.push(meal);
}
});
} else {
// get meals if no results
this.getMeals(); // call your get meals function or call the old meals array
}
this.setState({
meals: mealsContent
});
}