简体   繁体   中英

How do I pass an array of objects that contains a component to child component in React with Typescript?

I need to make Accordion component reusable. In the future I should be able to add new object to the same array 'accordionProps' and pass it down to accordion.

Here I'm passing an array 'accordionProps' of objects down to component. Prop types are defined in child component Accordion which matches my array content.

     const accordionProps = [
    {
      title: 'Active Orders',
      body: <OrderModule />,
    },
    {
      title: 'Drivers',
      body: <DriverModule />,
    },
  ];

  return (
    <DashboardWrapper>
      <Accordion title={title} body={body}/>
      <Map />
    </DashboardWrapper>
  );
};

export default Dashboard;

Still TypeScript throws an error: Type '{ accordionProps: { title: string; body: Element; }[]; }' is not assignable to type 'IntrinsicAttributes & accordionProps'. Property 'accordionProps' does not exist on type 'IntrinsicAttributes & accordionProps'.

It doesn't work when I do pass props as {...accordionProps} either.

Here is what my child component Dashboard looks like:

import { Component } from 'react';

type accordionProps = [
  {
    title: string;
    body: Component;
  },
];

const Accordion = (props: accordionProps) => {
  return (
    <AccordionContainer>
      {props.map(section => (
        <div key={section.title}>
          <div>{section.title})</div>
          <div>{section.body}</div>
        </div>
      ))}
    </AccordionContainer>
  );
};

export default Accordion;

I can't figure why TS is not letting me do that.

Does anyone know if an abstraction like that is even possible in React?

Help is really appreciated.

You declared your prop types as an array with one object in it:

type AccordionProps = [
  {
    title: string;
    body: Component;
  },
];

However, react props must be an object:

type AccordionProps = {
  title: string;
  body: Component;
},

Then, in order to render an array of items, you need to map over the array of props, rendering the component you want in each iteration of the loop.

For example, assuming you had:

  // declare an array of AccordionProps objects
  const accordionProps: AccordionProps[] = [
    {
      title: 'Active Orders',
      body: <OrderModule />,
    },
    {
      title: 'Drivers',
      body: <DriverModule />,
    },
  ];

Then you might render those like so:

<>
  { accordionProps.map(props => <Accordion {...props} />) }
</>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM