Search code examples
reactjstypescriptmultidimensional-arrayforeachreact-props

Passing props to a component from nested array in React


I have a nested array like below. Accordion should be displayed according to the no. of array I have and the accordion summary would contain the details 'Title' , 'TotalPrice'. Whereas accordion details would contain the 'subcontents', 'Subtitle' and 'SubtitlePrice'.

let summaryContents: any[] = [
{
  Title: "Construction costs",
  TotalPrice: "$25000",
  Subcontents: [
    {
      Subtitle: "Sanitation",
      SubtitlePrice: "$5000",
    },
    {
      Subtitle: "PoolLights",
      SubtitlePrice: "$5000",
    },
    {
      Subtitle: "PoolCleaner",
      SubtitlePrice: "$15000",
    },
  ],
},
{
  Title: "Pool interior costs",
  TotalPrice: "$20000",
  Subcontents: [
    {
      Subtitle: "Title1",
      SubtitlePrice: "$5000",
    },
    {
      Subtitle: "Title2",
      SubtitlePrice: "$10000",
    },
    {
      Subtitle: "Title3",
      SubtitlePrice: "$5000",
    },
  ],
}

I will have to make pass these values as props to another component. If it is within the component I know we can do something like this

return (
<>
  {summaryContents.map((item: any) => {
    <>
      {item.Title}
      {item.TotalPrice}

      {typeof item.Subcontents == "object" ? (
        <>
          {item.Subcontents.map((subItem: any) => (
            <>
              {subItem.Subtitle}
              {subItem.SubtitlePrice}
              
            </>
          ))}
        </>
      ) : null}
</>;
  })}

</>


 );

What can we do to pass it another component like the one given below

<QuoteSummary
  Title={item.Title}
  TotalPrice={item.TotalPrice}
  Subtitle={item.Subcontents.Subtitle}
  SubtitlePrice={item.Subcontents.SubtitlePrice}
/>

Solution

  • Well, this might help you.

    // your parent component
      return (
        <>
          {summaryContents.map((item: any) => {
            return <QuoteSummary
              Title={item.Title}
              TotalPrice={item.TotalPrice}
              Subcontents={item.Subcontents}
            />
          })}
        </>
      );
    
    // Your child1 component
    const QuoteSummary = ({ Title, TotalPrice, Subcontents }) => {
      return (
        <>
          {Title}
          {TotalPrice}
          {Subcontents.map((item: any) => {
            return <SubContent
              Subtitle={item.Subtitle}
              SubtitlePrice={item.SubtitlePrice}
            />
          })}
        </>
      );
    }
    
    // Your child2 component 
    const SubContent = ({ Subtitle, SubtitlePrice }) => {
      return <>
        {Subtitle}
        {SubtitlePrice}
      </>
    }