1

I want to import only the components that are present in a list.

A list contain all value checked by a user

for example, here is the default list :

const Defaultlist = [
    {
      name: 'test one',
      id: 1,
      componentName: 'TestOne',
    },
    {
      name: 'test two',
      id: 2,
      componentName: 'TestOne',
    },
  {
      name: 'test three',
      id: 3,
      componentName: 'TestThree',
    },
  ];

and here the selection from my user

 const List = [
    {
      name: 'test one',
      id: 1,
      componentName: 'TestOne',
    },
    {
      name: 'test two',
      id: 2,
      componentName: 'TestTwo',
    },
  ];

I was thinking of mapping and create a dynamic component as below, But how can I make “dynamic” import ? Am I on the good way if I do it like that ?

import React from 'react';
import { useSelector } from 'react-redux';
//import { OneComponent } from `./${dd}`;

export const ListChoice = ({ control, watch }) => {

  const langue = useSelector((state) => state.langue.langueSelected);
  const List = watch('user.list');

  return (
    <div>
      <h2 className="title">{langue?.pleaseSelect}</h2>
      {List?.map((el) => {
        const OneComponent = el.componentName;
        return <OneComponent />;
      })}
    </div>
  );
};
3
  • you have to find the way to do this by the props, and not by the component. The component have to exsits, of course. XD. ¿how many diferents components it can be there ? refactor your compoenet vía props to if you really need this. Commented Feb 16, 2023 at 9:22
  • 1
    I actually did this : {servicesList?.map((el) => { const { PathName } = require('../' + el.pathName); return <PathName />; })} Commented Feb 16, 2023 at 9:26
  • and works good ? Commented Feb 16, 2023 at 9:28

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.