2

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 />)}

2 Answers 2

2

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'/>)
Sign up to request clarification or add additional context in comments.

Comments

2

You will need to use an object as components map, something like this :

const componentsMap = {
  "server": Server,
  "route": Route,
  "volume": Volume
}

{str.map(key => {
  const TheComponent = componentsMap[key];
  return <TheComponent />
})}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.