0

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.

Vad
  • 3,658
  • 8
  • 46
  • 81
  • What have you tried? Pls show so we can help with any issues you have found – StudioTime May 08 '17 at 15:24
  • I added more info to my question but I have not tried since I cannot find any answer to my question. – Vad May 08 '17 at 15:34
  • You should run the ajax call to get the external data inside a `componentDidMount()` function then set your state when it's received the data – StudioTime May 08 '17 at 15:39
  • "Updating the front end" is a large fraction of everything React does. Can you be more specific to what is giving you trouble? – Tim Grant May 08 '17 at 15:54
  • Yes, thanks. Imagine I want to update a DIV container with some content delivered from a third party service call (see response above) and after I add it to DOM, I want to make sure it persists - stays updated in React's DOM – Vad May 08 '17 at 16:09

1 Answers1

0

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.

speckledcarp
  • 6,196
  • 4
  • 22
  • 22
  • But this is React Component way, isn't it? How can I do it knowing CSS selector, and then update React Virtual DOM? – Vad May 08 '17 at 19:08
  • I'm not quite sure what you mean. Why is it necessary to update based on a CSS selector? Idiomatic React takes all information necessary to render a component as props, or maintains it as local state. – speckledcarp May 08 '17 at 19:25
  • because that's how a third party service delivers content to my app. – Vad May 09 '17 at 14:04
  • Is the div container you're trying to update being generated by your React code? If so, ignore the selector and just adjust your render to render based on the info you get back (possibly using the code above). If the div is *not* being generated by your React code, I'd keep React completely out of the loop. – speckledcarp May 09 '17 at 14:45