Home > Blockchain >  Dynamic render react child component
Dynamic render react child component

Time:05-22

How can i dynamic render react child component? Now that looks like this and its works.

<CustomFieldArea>
                    {(ExampleCustomFields || []).map((e: {
                        field: string;
                        CustomComponent: 'Text' | 'TextArea'
                    }) => {

                        if (e?.CustomComponent === 'Text') {
                            return (
                                <CustomFieldArea.Text
                                    name={e?.field}
                                />
                            )
                        }

                        if (e?.CustomComponent === 'TextArea') {
                            return (
                                <CustomFieldArea.TextArea
                                    name={e?.field}
                                />
                            )
                        }

                    })}
                </CustomFieldArea>

Here is the output I’m looking for:

<CustomFieldArea>
                    {(ExampleCustomFields || []).map((e: {
                        field: string;
                        CustomComponent: 'Text' | 'TextArea'
                    }) => {
                        return (
                                <CustomFieldArea[e?.CustomComponent]
                                    name={e?.field}
                                />
                            )
                    })}
                </CustomFieldArea>

But it doesnt work. How can i using <CustomFieldArea[e?.CustomComponent] label={e?.title}> like this.

CodePudding user response:

Are you want something like render props ?

<DataProvider render={data => (
  <h1>Hello, {data.target}</h1>
)}/>



<Mouse children={mouse => (
     <p>Current mouse position: {mouse.x}, {mouse.y}</p>
)}/>

Read more here

if render props isn't that you want then Use HOC's

const menu = [
  { title: 'Home', icon: 'HomeIcon' },
  { title: 'Notifications', icon: 'BellIcon' },
  { title: 'Profile', icon: 'UserIcon' },
]

const Icon = (props) => {
  const { name } = props

  let icon = null
  if (name === 'HomeIcon') icon = HomeIcon
  if (name === 'BellIcon') icon = BellIcon
  if (name === 'UserIcon') icon = UserIcon

  return React.createElement(icon, { ...props })
}

Read more here

Helpful links

  • Related