Home > database >  How can I separate the JSX mapping logic from the mapped array containing components with props?
How can I separate the JSX mapping logic from the mapped array containing components with props?

Time:04-22

I have a component that maps over an array of components that have props passed into them, something along these lines:

const Component = (prop0, prop1, prop2) => {

  const array = [
    {
      id: 0,
      component: <SubComponent0 prop0={prop0}>
    },
    {
      id: 1,
      component: <SubComponent1 prop1={prop1}>
    },
    {
      id: 2,
      component: <SubComponent2 prop2={prop2}>
    }
  ];

  return (
    {array.map(obj => 
      <div key={obj.id}>
        {obj.component}
      </div>
    )}
  );
};

export default Components;

I would like to separate the array into its own JS file that I import in, which worked fine for me in other cases where the components involve no props, but in this case I run into the problem of the props being undefined outside of the scope of this functional component, and I can't figure out how I can import/pass those props into the new JS file where I put the array. Is that possible to do, or is there another way for me to move the array into a separate file? Thanks.

CodePudding user response:

An approach to that could be to use a default function that builds the data and then returns everything.

data.js

const getData = (prop0, prop1, prop2) => {
  return [
  {
    id: 0,
    component: <SubComponent0 prop0={prop0}>
  },
  {
    id: 1,
    component: <SubComponent1 prop1={prop1}>
  },
  {
    id: 2,
    component: <SubComponent2 prop2={prop2}>
  }
];
}

module.exports = getData;

App.js

const getData = require('data.js');
const Component = (prop0, prop1, prop2) => {

  const array = getData(prop0, prop1, prop2);

};

CodePudding user response:

I think you can also try Dynamic component means Component name from String I never implemented but I search little and prepare solution as below. You can try and let us know if it works

data.js

import { lazy } from 'react';
const getData = (props) =>{

const array = props.map((item,index) => {
    const DynamicComponent = lazy(() => import(`./SubComponent${index}`));
    return {
        id : index,
        component : <DynamicComponent prop=`prop${item}` />
    }
});

return array
}
export default getData;

App.js

import getData from './data.js';

const Component = (...props) => {

const array = getData(props)

return (
{array.map(obj => 
  <div key={obj.id}>
    {obj.component}
  </div>
)}
);
};

export default Component;
  • Related