Blog>
Snippets

Dynamic Component Handling with React

Use React's component mapping to dynamically render components, providing a default component when an unknown component is specified.
import React from 'react';
Import React from the 'react' package.
const componentsMap = {
  ComponentA: () => <div>A Component</div>,
  ComponentB: () => <div>B Component</div>,
  // ... more components here
  DefaultComponent: () => <div>Unknown Component</div>,
};
Create a mapping of component names to component functions, with a fallback for unknown components.
const DynamicComponent = ({ componentName }) => {
  const Component = componentsMap[componentName] || componentsMap.DefaultComponent;
  return <Component />;
};
Define a DynamicComponent that takes a component name as a prop and looks it up in the componentsMap, rendering the specified component, or the default if not found.
const App = () => (
  <div>
    <DynamicComponent componentName='ComponentA' />
    <DynamicComponent componentName='ComponentB' />
    <DynamicComponent componentName='ComponentC' />
  </div>
);
Use the DynamicComponent inside the App component, specifying the names of the components to render, demonstrating how the dynamic rendering works, including a fall-back to the default when 'ComponentC' is not found in the map.