Dynamically rendering a component using an object
I'm currently building a React/Next application that's connecting to a CMS. The CMS gives the structure of the website in JSON and our job is to translate this to React components. Each "JSON component" has a unique
name
property that's being used to match the "JSON component" with the correct React component.
Let's say we have two components, ComponentA
and ComponentB
.
ComponentA
has the following properties
https://codesandbox.io/s/react-typescript-forked-vurizt?file=/src/components/ComponentA.tsx:29-75
ComponentB
has the following properties:
https://codesandbox.io/s/react-typescript-forked-vurizt?file=/src/components/ComponentB.tsx
We combine these properties into one type:
https://codesandbox.io/s/react-typescript-forked-vurizt?file=/src/helpers/types.ts:119-233
By doing so, we can easily render the correct component using a switch
-statement
https://codesandbox.io/s/react-typescript-forked-vurizt?file=/src/helpers/renderComponentWithSwitch.tsx
This is all great, but this would result in one big switch
-statement and it can become quite the mess. We would like to use an object with a key-value pair. The key being the unique name
property and the value the component that needs to be rendered.
However, I can't quite figure out how to do this properly. The code is working, but TypeScript is throwing an error as it can't match the correct name with the value:
https://codesandbox.io/s/react-typescript-forked-vurizt?file=/src/helpers/renderComponentWithObject.tsx:463-497
Can someone help me with this?
Thanks!1 Reply
Figured it out from the TS Discord 🙌
Also updated the CodeSandbox for everyone not sure how to fix it themselves