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?

3
  • Why do you need to use JSX if you are already putting it into a string? Commented Mar 4, 2015 at 0: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, 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 "<MyComponent />, you need another solution that I don't know. Commented Jan 3, 2022 at 23:36
  • Does this answer your question? Dynamic tag name in React JSX Commented Jul 10, 2022 at 11:16

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

i'm having the same problem but var ContentBlocks = { info : require('./Infoblock'), portrait : require('./Portraitblock') }; and <ContentBlocks['info']> throws an error
I just checked and you're right, you can use <ContentBlocks.info> or alternatively do var MyComponent = MyComponents['info']; and <MyComponent> if the key isn't known when you're writing it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.