Home > Mobile >  How to send a component as an argument to a function in another component?
How to send a component as an argument to a function in another component?

Time:11-11

In my case, I have a components '1,2,3,....' imported in another main component 'A'. In component 'A' some operation is done and among the components '1,2,3...' one filtered component is returned.

I have to send some props to this filtered components and render this filtered component. Am posting my code please have a look. Thank you.

const LineItemViewComponent = [{
  lineItem: "AR008",
  component: <AR008Users />,  
},{
  lineItem: "AR009",
  component: <AR009Users />,
},{
  lineItem: "AR010",
  component: <AR010Users />,
},];

const filterData = LineItemViewComponent.filter((eh) => eh.lineItem === this.props.each.lineItem);
const viewDataFunction = () => {
  const {component} = filterData
  return <>
  <component assessClicked={assessClicked}
        count={this.state.count}
        setAssessApi={this.setAssessApi} />
  </>;
};

AR008Users and AR009Users are the exported components.

What I am expecting is to use the filtered component to render JSX data and want to send props to that component, like this:

<component assessClicked={assessClicked}
        count={this.state.count}
        setAssessApi={this.setAssessApi} />

CodePudding user response:

In your object you should use a reference to the Components and not use jsx to instantiate them.

Then in your rendering part, you should use either find or extract the [0] item, because filter returns an array.

Finally you should capitalize the component variable.

so

const LineItemViewComponent = [
  {
    lineItem: "AR008",
    component: AR008Users
  },
  {
    lineItem: "AR009",
    component: AR009Users
  },
  {
    lineItem: "AR010",
    component: AR010Users
  }
];

const filterData = LineItemViewComponent.find(
  (eh) => eh.lineItem === this.props.each.lineItem
);
const viewDataFunction = () => {
  const { component: Component } = filterData;
  return (
    <>
      <Component
        assessClicked={assessClicked}
        count={this.state.count}
        setAssessApi={this.setAssessApi}
      />
    </>
  );
};

CodePudding user response:

Try like this (make sure you export the components that will be imported with default export):

const LineItemViewComponent = [{
  lineItem: "AR008",
  component: AR008Users,  
},{
  lineItem: "AR009",
  component: AR009Users,
},{
  lineItem: "AR010",
  component: AR010Users,
},];
  • Related