Update React App Dynamically with JavaScript

723 views Asked by At

My React app makes a third party service call to load content that needs to be injected into DOM by specified CSS selector. It can be anywhere on the page. How exactly can I inject this content into React app by specified selector to make sure Virtual DOM gets updated and remains unchanged?

Imaging, this is the third party response object that I want to inject into React app:

var response={selector:'#someSel',html='<div>Hello from third party</div>'}

I am somewhat new to React world but I am familiar with Virtual DOM challenges when updating the app dynamically. I want React to make update on the front end to inject this content - when React app has all components already updated.

Please note that I can modify the app however I need to to get it working.

1

There are 1 answers

4
speckledcarp On

I think dangerouslySetInnerHTML might be what you're looking for.

The official React docs use the following example.

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

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

Of course, in your case, you'd be setting __html in createMarkup() with the HTML content from your third party.