MarksCode
MarksCode

Reputation: 8584

Combine markup with jsx

I have an array in which certain elements are strings that represent markup like "<p>Hello there</p>" and other elements are JSX. I need to render a div with all those elements in their correct order corresponding to their index in the array. The reason I need to do this is because the JSX elements are elements I've parsed out from the rest of the raw HTML and added functionality to such as onClick.

I know for markup you can use dangerouslySetInnerHTML and for jsx you can just insert it like this:

<div>
  {myArrayOfComponents}
</div>

However, is there a way to combine the two to make a div made up of both markup and JSX?

Upvotes: 1

Views: 665

Answers (1)

Courtney7
Courtney7

Reputation: 348

The following should go in the render method of a React class or be a React functional component. To maintain the order of your original array, just use a map function which acts on each element of the array, creating a new array of the same size and order but with newly mapped elements. Do type detection on each element in the array to determine if it is a string (to convert to a JSX React component) or already a JSX React component (do nothing). Finally, return the new array inside a div.

var elements = ['<p>Test HTML</p>', <p>Test JSX</p>].map(function(element) {
  if (typeof(element) === 'string') {
    return (<span dangerouslySetInnerHTML={{__html: element}}></span>);
  } else {
    return element;
  }
});
return (
  <div>{elements}</div>
)

Just replace my array in the first line with yours to use it.

Code Sandbox Example

Upvotes: 3

Related Questions