'How to re-render a component on an event of an another unrelated component
I have a React app & component structure looks like below
productsList.component.ts
export const ProductsListComponent = () => {
const [category, setcategory] = useState("retail");
const [products, setProducts] = useState([]);
const categorySelectHandler = (selectedCategory:string) => {
setcategory(selectedCategory);
}
useEffect(() => {
getProductsByCategory(category).then((products) => {
setProducts(products);
}
});
}, [category]);
return (
<ProductsContext.Provider value={{products:products}}>
<CategorySelector onCategorySelected={categorySelectHandler} products={products}></CategorySelector>
<Product products={products}></Product>
</ProductsContext.Provider>)
product.component.ts
export const Product = () => {
const ctx = useContext(ProductsContext);
const [products, setProducts] = useState(ctx.Products);
return (
<>
{ products.map((product) => {
return (
<div>
<b> {product.name} </b>
<i> {product.price} </b>
}
}
</<>
categorySelector.component.ts
const CategorySelector: React.FC <CategorySelectorProps> = ({
onCategorySelected,
products
}) => {
const ctx = useContext(ProductsContext);
const quantityHandler = (e) => {
const quantity = e.target.value()
//doing some calculations here & updating the products array
ctx.products = []; //new array
}
return (
<div>
{
//needing to display the products name here some business reason
products.map(product => <p> product.name </p>
}
<input type="text" onChange={quantityHandler} name="Quantity" />
</div>
)};
export default CategorySelector;
Here
onChangeevent of the textbox in CategorySelector component, I am doing some BL calculations & updating theproductsarray & on this I need to re-render the Product Component without re-rendering the CategorySelector component.
Thanks!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
