Markus
Markus

Reputation: 4242

React: Create Elements/Tags programmatically / Create React Element from String?

I am looking for the equivalent of creating of HTML Tags step by step (concatenating them) like below in React:

var result="";
result += "<div>"; 
result += "dd";
result += "</div>"; 

Something like the following, but this is not working. I tried with an array, but it did also not work...

function MyComponent(props) {

   var result;
   result += <div>; 
   result += "dd";
   result += </div>;   

   return result; 
}

Thanks very much!

Upvotes: 0

Views: 438

Answers (1)

Dennis Vash
Dennis Vash

Reputation: 53884

Try using dangerouslySetInnerHTML, official example:

function createMarkup() {
  return {__html: 'First &middot; Second'};
}

function MyComponent() {
  return <div dangerouslySetInnerHTML={createMarkup()} />;
}

In your case:

function MyComponent(props) {

   var result;
   result += "<div>"; 
   result += "dd";
   result += "</div>";   

   return <div dangerouslySetInnerHTML={{__html: result}}></div>; 
}

Additionally, you can look for any string-to-jsx library for use.

Upvotes: 1

Related Questions