4

I am looking to render a component based upon a string. Essentially, I am hoping to find the JSX equivalent to JavaScript's dynamic function name ability (parent["childMethod"]).

So, if I have a string, such as "<MyComponent />", how can I turn into JSX and render?

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Matt Fordham
  • 3,147
  • 10
  • 34
  • 51
  • Why do you need to use JSX if you are already putting it into a string? – David Hellsing Mar 04 '15 at 00:02
  • Your title and your second paragraph present different problems. If you've specifically got a *component name* in a string, as implied by your title, you can (assuming your build pipeline doesn't minify or otherwise change component names) create an *element* from it with [`React.createElement`](https://facebook.github.io/react/docs/react-api.html#createelement), store that element in a variable, and include the element within some JSX using curly braces. If you have the entire JSX code for an element in a string, though, like `"`, you need another solution that I don't know. – Mark Amery Jan 03 '22 at 23:36
  • Does this answer your question? [Dynamic tag name in React JSX](https://stackoverflow.com/questions/33471880/dynamic-tag-name-in-react-jsx) – Aryan Beezadhur Jul 10 '22 at 11:16

1 Answers1

7

JSX is just a nice syntax for function calls, so you need to have the actual functions to use a component. If you have an object that contains React components then you can render a component based on a string property. For example if you have an object called MyComponents (has to be uppercase for JSX) and that object has React components like MyComponents.SomeInput = React.CreateClass(...). Then you can use <MyComponents.SomeInput /> in your JSX.

Scott
  • 860
  • 8
  • 10
  • i'm having the same problem but ```var ContentBlocks = { info : require('./Infoblock'), portrait : require('./Portraitblock') };``` and `````` throws an error – Jörn Jul 12 '15 at 22:43
  • 1
    I just checked and you're right, you can use `` or alternatively do `var MyComponent = MyComponents['info'];` and `` if the key isn't known when you're writing it. – Scott Jul 20 '15 at 05:48