0

I have a fairly complete application written in React. To better maintain the codebase going forward, I have decided to migrate the whole project to TypeScript. In my code, I dynamically render a collection of components onto the page based on a selection. In JS, this works flawlessly, but in TS, it throws error. Any help would be appreciated.

import AppListTable from './AppListTable';
import B from 'B';
import C from 'C';

const COMPONENTS = {
    AppListTable
    B,
    C
}

var selectedComponents = [{component:'A'},{component: 'C'}];

const components = selectedComponents.map( (val,index) => {
        const TempComponent = COMPONENTS[val.component];
        return <Route key={index} exact path={val.url}><TempComponent /></Route>
    })

render ( {components} );

Note that I can't share the whole codebase, but this is the part this is having issues. Hovering over COMPONENTS give me this error: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ AppListTable: () => Element; }'. No index signature with a parameter of type 'string' was found on type '{ AppListTable: () => Element; }'

tscrip
  • 140
  • 3
  • 14
  • https://stackoverflow.com/questions/58123398/when-to-use-jsx-element-vs-reactnode-vs-reactelement – ksav Sep 14 '20 at 02:09

1 Answers1

0

For all who run into this same problem, I ended up doing this to solve the problem.

let COMPONENTS: {[name: string]: React.FC} = {};
COMPONENTS[AppListTable.name] = AppListTable;

You can now access the component via: const TempComponent = COMPONENTS[componentName];

tscrip
  • 140
  • 3
  • 14