Fotios Tragopoulos
Fotios Tragopoulos

Reputation: 478

How to dynamically order my react components according to the order I get from my request?

I would like to transfer the responsibility of the order of my components to be passed to the .JSON file I GET from my request. In the following component, I get a list of 2 components with names Component1 and Component2 and their data component1_data and component2_data accordingly. How can I put my components in the same order that they are on this list?

Also, there is an if-else statement which is pushing the relevant content to the appropriate list. How can I write this more efficient so I will remove the repetition?

import React from 'react';
import Component1 from '../component1';
import Component2 from '../component2';

const Landing = (props) => {

    const component1_data = [];
    const component2_data = [];

    if (data) {
        for (let i = 0; i < data.length; i++) {
            if (data[i].component_type === 'component1') {
                const contentElement = data[i];
                component1_data.push({ ...contentElement, content: props.data[contentElement.content] });
            } else if (data[i].component_type === 'component2') {
                const contentElement = data[i];
                component2_data.push({ ...contentElement, content: props.data[contentElement.content] });
            }
        }
    }

    return (
        <div>
            <Component1 data={component1_data} />
            <Component2 data={component2_data} />
        </div>
    );
}

export default Landing;

"landing": [
      {
        "component_type": "component2",
        "content": "component2"
      },
      {
        "component_type": "component1",
        "content": "component1"
      }
    ]

Upvotes: 2

Views: 1148

Answers (1)

Zachary Haber
Zachary Haber

Reputation: 11047

Here's a basic rundown on a better way of doing it: map your data into the components that you want to render. Then you can output that directly in the JSX.

import React from 'react';
import Component1 from '../component1';
import Component2 from '../component2';
// This is a mapping between the contentElement strings to the Component you want to render
const componentMap = {
  component1: Component1,
  component2: Component2,
};
const Landing = (props) => {
  const components = data.map((datum) => {
    const ComponentType = componentMap[datum.contentElement];
    if(!ComponentType) return null;
    // This returns the component you want with the data
    // If the props aren't set up how you want, you should be able to modify it to have the right names
    return (
      <ComponentType data={{ ...datum, content: props.data[datum.content] }} />
    );
  });

  return <div>{components}</div>;
};

export default Landing;

Upvotes: 3

Related Questions