Home > front end >  Pass trough props only one property in typescript react
Pass trough props only one property in typescript react

Time:10-12

I have a parent component and I need to pass trough props only the product name property into my "Title" component so then I don't have to loop the info inside my children component.

Here I have an image to explain my problem Code image


const DetailView = () => {
  const [products, setProducts] = useState<Product[]>([])

  return (
    <>
      {products.length > 0 ? (
        <>
          <Title products={ need to access product image here  } />
          <Header products={products} />
          <Grid container>
            <Grid item xs={12} sm={12} md={4} lg={4}>
              <ProductImage products={products} />
            </Grid>
            <Grid item xs={12} sm={12} md={8} lg={8}>
              <Results products={products} />
            </Grid>
          </Grid>
          <Grid container>
            <Chart />
          </Grid>
        </>
      ) : (
        'Loading...'
      )}
    </>
  )
}

And here is the type interface Product


export interface Product {
  _id: string
  _index: string
  _score: number
  _shop: {
    alias: string
  }
  _similarity_percentage: number
  _source: {
    g_shop_name: string
    product_match_token: string
    product_last_data: {
      product_id: string
      product_url: string
      product_created_at: string
      product_images_list: string[]
      product_name: string
      product_price_currency: string
      product_price_description: string
      product_price_value: number
      product_prices_list: any[]
      category_name: string
      product_brand_name: string
      g_shop_name: string
      _type: string
    }
  }
}

CodePudding user response:

<Title products={products.map(p => p._source.product_last_data.product_name)} />

This will pass through an array of strings :)

CodePudding user response:

Maybe this is what you are looking for! first, change the Title component props type to this

interface ITitleProps {
    productsNames: string[],
}

then what you can do just simply extract the property from your products.

// using state
const [productsNames, setProductsNames] = useState<string[]>([]);
useEffect(() => {
   setProductsNames(products.map(p => 
   p._source.product_last_data.product_name));
}, [products])
// pass to Title component
<Title productsNames={productsNames}>

// OR using re-rendering of react
// in your return statement
<Title productsNames={products.map((p) => p._source.product_last_data.product_name)}/>

Hope this will resolve your problem.

  • Related