Home > Software design >  React TypeScript: Passing components in an Array as props
React TypeScript: Passing components in an Array as props

Time:05-18

I am looking for a solution in TypeScript React to pass multiple components in an array. I have declared interfaces and importing it inside my component. But it gives me an error as 'Type 'Element' has no properties in common with type 'IDataView''.

I have added code snippet to what steps i am following. I am not sure what am i missing in the below code.

My Parent Component:

    const DataViewContainer:React.FC = () => {
 return (
    <ViewCollection views={[<BarChart />, <LineChart />]} />
 )
}

Child Component :

interface IViewCollection {
 views: IDataView[]
}
interface IDataView {
 barChartView?: React.ReactNode;
 lineChartView?: React.ReactNode;
}

const ViewCollection = (views: IViewCollection): JSX.Element => {
 return (
    <Carousel>
       {views.map((cmp) => { return (cmp) }}
    </Carousel>
 )
}

CodePudding user response:

According to your type, you suppose to pass an object. Notice the fixes of props, views and the usage inside ViewCollection component.

const DataViewContainer: React.FC = () => {
  return (
    <ViewCollection
      views={{ barChartView: <BarChart />, lineChartView: <LineChart /> }}
    />
  );
};

const ViewCollection = (props: IViewCollection): JSX.Element => {
  return (
    <Carousel>
      {props.views.barChartView}
      {props.views.lineChartView}
    </Carousel>
  );
};

  • Related