Search code examples
javascriptreactjscomponentsreact-propsarray.prototype.map

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


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.


Solution

  • 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);
    
    };