I have a search bar component Search.jsx
import { useEffect, useState } from 'react'
export default function Search() {
const [query, setQuery] = useState('')
return (
<div className={styles.container}>
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material Icons"></link>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Inter" />
<form className={styles.search_bar} action="">
<input type="text" placeholder="e.g. Adobo" onChange={event => setQuery(event.target.value)} />
<button><i className="material-icons">search</i></button>
</form>
</div>
)
}
and I want to filter the results that show up in my Card.jsx
import styles from "./Card.module.css";
import { useEffect, useState } from 'react'
export default function Card() {
const [menus, setMenus] = useState([])
useEffect(() => {
fetch("https://api.jsonbin.io/v3/b/63863ca77966e84526cf79f9")
.then((res) => res.json())
.then((data) => {
setMenus(data)
})
}, [])
return (
<div className= {styles.card_container}>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Inter" />
{menus.record?.map( menu => (
<div className={styles.container}>
<div key ={menu.title} className={styles.img_container}>
<img className={styles.card_img} src={menu.image} alt="Food Image"/>
</div>
<h1 className={styles.card_title}>{menu.title}</h1>
<h1 className={styles.card_body}>
{menu.body}
</h1>
<h1 className={styles.card_price}>{menu.price}</h1>
<button className={styles.card_button}> Add to Order </button>
</div>
))}
</div>
)
}
I tried using the filter method but I really don't know how to implement it between two components.
CodePudding user response:
Do you want to use the search component inside card component and filter the menu items based on the search selected is the requirement?
CodePudding user response:
In order to filter the results in your Card component using the Search component, you'll need to pass the query state from the Search component to the Card component. Here's one way you can do that:
- In the
Searchcomponent, add aonSubmitevent handler to the form that passes thequerystate to a function passed in as a prop from the parent component: - In the parent component, pass the
querystate to theCardcomponent as a prop and add afilteredMenusstate that contains the menus filtered using thequeryprop: - In the
Cardcomponent, update themenusstate to use the menus prop instead of the local state:
