Search code examples
arraysreactjsreact-component

react convert strings to react components


So this might be kinda weird, I have an array of strings and a bunch of React components as well. For example:

const str = ['server','volume','route']

const Server = () => 'This is a server'
const Volume = () => 'This is a server'

and so forth, you get the idea.

I am trying to map the str to matching react Components and return the components.

I know I can use a loop and a switch to check for each item and return the respective component, but is there any creative idea like this:

{str.map(Y => <Y />)}

Solution

  • Not a very common use case, but definitely possible. First turn all items into components

    const data = const str = ['server','volume','route']
    const components = data.map(x => props => <div {...props}>{x}</div>)
    

    Now render each one

    return components.map((Component, i) => <Component key={i} customProp='foo'/>)