AlaaKudo810
AlaaKudo810

Reputation: 163

Passing a function from a react component to its parent then from the parent to another child

I have a component named Products, and it has this function declared in it:

const filterBySearch = (value: string) => {
    setAllProducts((prevProducts) => {
        const filtered = sourceProducts.filter((product) =>
            product.name.toLowerCase().includes(value.toLowerCase())
        );
        return filtered;
    });
};

I also have 2 other components, Navbar, and App, the Navbar contains a search input field, I want things to work in a way that whenever the value of that input inside the Navbar changes, the FilterBySearch function is called with the input value as its argument. The problem is that Navbar is neither a child of Products nor a parent, but they're both children of the App component. How do I pass the FilterBySearch from Products to App then from App to Navbar ?

Upvotes: 0

Views: 64

Answers (1)

Shakya Peiris
Shakya Peiris

Reputation: 612

Rather than passing the function you can set up the filterBySearch function inside the App component with the products state and call the function inside the Navbar component inside the change event listener of the input element.

Next, pass the allProducts state to the Products components

const App = () => {
    const [allProducts, setAllProducts] = useState([]);
    const filterBySearch = (value: string) => {
        setAllProducts((prevProducts) => {
            const filtered = sourceProducts.filter((product) =>
                product.name.toLowerCase().includes(value.toLowerCase())
            );
            return filtered;
        });
    };
    return (
        <Navbar filterBySearch={filterBySearch}  />
        <Products allProducts={products} />
    )
}

const Navbar = ({filterBySearch}) => {
    return <input onChange={(e) => filterBySearch(e.target.value)} />
}

const Products = ({allProducts}) => {
    //...
}

Or

You can define the function inside the Navbar component and pass the setAllProducts function as a prop to the Navbar component

const App = () => {
    const [allProducts, setAllProducts] = useState([]);
    
    return (
        <Navbar setAllProducts={setAllProducts}  />
        <Products allProducts={products} />
    )
}

const Navbar = ({setAllProducts}) => {
    const filterBySearch = (value: string) => {
        setAllProducts((prevProducts) => {
            const filtered = sourceProducts.filter((product) =>
                product.name.toLowerCase().includes(value.toLowerCase())
            );
            return filtered;
        });
    };
    return <input onChange={(e) => filterBySearch(e.target.value)} />
}

const Products = ({allProducts}) => {
    //...
}

Upvotes: 1

Related Questions