Issue
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.
Solution
It seems like you want to access query
inside the Card
component so that you can filter the list of items.
You can achieve this by lifting the query
state inside a parent component and passing query
and setQuery
as props, like so:
function App() {
const [query, setQuery] = useState('')
return (
<div>
<Card query={query} />
<Search query={query} setQuery={setQuery} />
</div>
)
}
Now your Search
component uses these props instead of its own state:
function Search({ query, setQuery }) {
And your Card
component, too:
function Card({ query }) {
...
{menus.record?.filter(el => /* some filtering with query */).map
Answered By - Jonathan Wieben
Answer Checked By - - David Marino (ReactFix Volunteer)