fabiobiondi

Create Dynamic Component (by JSON)

Oct 21st, 2020
882
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import React, { FunctionComponent, FunctionComponentElement, useEffect, useState } from 'react';
  2. import cn from 'classnames';
  3.  
  4. export const WidgetProfile = (props: any) => {
  5.   return <div style={{ color: props.color}}>
  6.     Profile {props.title}
  7.     <button onClick={() => props.onAction(123)}>go to profile</button>
  8.   </div>
  9. }
  10.  
  11. export const WidgetChart = (props: any) => {
  12.   return <div>Chart {props.title} {props.children}</div>
  13. }
  14.  
  15. export const Tabbar = (props: any) => {
  16.   return <div>
  17.     {
  18.       props.items.map((item: any) => <li key={item} onClick={() => props.onAction(item)}>{item}</li>)
  19.     }
  20.     {props.active}
  21.   </div>
  22. }
  23.  
  24. const COMPONENTS: { [key: string]: FunctionComponent<{ title: string }> } = {
  25.   chart: WidgetChart,
  26.   profile: WidgetProfile,
  27.   tabbar: Tabbar,
  28. }
  29.  
  30. const dashboard: any = [
  31.   {
  32.     component: 'profile',
  33.     data: { id: 1, title: 'yo!', color: 'red' }
  34.   },
  35.   {
  36.     component: 'chart',
  37.     data: { id: 2, title: 'sono un chart!' }
  38.   },
  39.   {
  40.     component: 'tabbar',
  41.     data: { id: 3, items: [10, 20, 30], active: 2 }
  42.   },
  43. ]
  44.  
  45. export default function App() {
  46.  
  47.   const onActionHandler = (componentType: string, params: any) => {
  48.     console.log('onActionHandler', componentType, params)
  49.   }
  50.   return <div>
  51.     {
  52.       dashboard.map((item: any, index: number) => {
  53.         console.log(item)
  54.  
  55.         const component: FunctionComponentElement<{ title: string}>
  56.           = React.createElement(
  57.             COMPONENTS[item.component],
  58.            { ...item.data, key: index, onAction: (params: any) => onActionHandler(item.component, params) }
  59.           )
  60.         return component;
  61.       })
  62.     }
  63.   </div>
  64. }
  65.  
RAW Paste Data