Search code examples
javascriptreactjsreact-props

How to pass returned value to different component


I'm trying to be able to load a product in a separate child component (which is enabled when a user clicks a product from a product list rendered map on the parent component).

I've set up a function to .filter through the list of products so just the product at the index value (that matches the ID of the product clicked from the product list) and return it in a variable.

In Parent Component

let focussedProduct = "";

const viewProduct = (productID) => {
  focussedProduct = focusProduct.filter((e, index, array)=>{
    return index == productID
  })
  console.log(focussedProduct[0]);
};
<div className='product' key={product.id} onClick={() => viewProduct(product.id)}>

Which console logs this, so it's returning what I need when clicking random items:

enter image description here

However I'm really struggling to pass the returned value/data to the child component to map it and start rendering that product, I thought it would be as easy as passing the variable like this.

Parent component

<Product 
  focussedProduct = {focussedProduct}
/>

Child component

import React, {useState} from "react";

const Product = (props) => {  
    console.log(props.focussedProduct)  
}

export default Product;    

But it's not returning anything in the console to use/map. So I'm guessing I'm doing something wrong and I'm sure it's simple but I'm not getting there even after doing a bit of googling. Help is much appreciated.


Solution

  • It seems your problem is that when you call viewProduct you update focussedProduct but it is not a state variable and no re-render happens.

    Actually you have access to the product during click so you could just directly store that in state without performing the filter.

    Or you could do as you have just additionally store the result (focussedProduct) in state, or you can just store id of the clicked item in state and perform filter during render as here:

    export default function Form() {
      const [id, setId] = React.useState('');
      const [items, setItems] = React.useState([
        { id: 'item1', label: 'label1' },
        { id: 'item2', label: 'label2' },
      ]);
    
      let focusedProduct = items.filter((x) => x.id === id)?.[0];
    
      return (
        <form>
          <div>
            {items?.map((y) => (
              <div
                onClick={() => {
                  setId(y.id);
                }}
              >
                {y.label}
              </div>
            ))}
          </div>
          {focusedProduct && <div>Clicked: {focusedProduct.label} </div>}
        </form>
      );
    }