0

So, I'm doing a little web app using React Typescript and I have one problem I'm unable to fix.

My app obtains from an external API (using a POST request) a plotly graph in text/html. What I need to do is to inject this HTML and JS in my React App in order to be displayed in the browser.

What is the best way to do this? I've tried different approaches and nothing seems to work. I think the HTML components are being rendered, but the JS isn't being executed.

I need to inject something using this structure. The code bellow is not completed.

<div>
<div id="div-1" class="plotly-graph-div" style="height:100%, width:100%">
Plotly.newPlot("div-1",...)
</div>
</div>

Thanks in advance :)

k3nz0
  • 7
  • 6

1 Answers1

1

try loading the html dynamically then.

const divElement = useRef();
useEffect(() => {
  if (divElement.current)
    divElement.current.innerHTML = "Your html and js will be executed"
}, [])

return ( <
  div className = "test"
  ref = {divElement}>
  </div>
)
Alen.Toma
  • 4,684
  • 2
  • 14
  • 31
  • I'm using functional components within React Typecsript, I'm unable to do that. – k3nz0 Dec 06 '21 at 13:48
  • 1
    I edited my answer and added a functional components. Have a look – Alen.Toma Dec 06 '21 at 16:02
  • Thank you very much for your answer. However when I tried that, the problem persists. The parent divs are rendered, but the plotly.js Javascript inside isn't executed. – k3nz0 Dec 06 '21 at 17:06
  • 1
    This should have worked, then it is something to do with your js file – Alen.Toma Dec 06 '21 at 18:17
  • For example. Your code injects the HTML correctly. But if I try to do something like this `divElement.current.innerHTML = '
    ';` when I open my console i don't see any console.log. In other words, the js isn't being executed. What am I doing wrong?
    – k3nz0 Dec 07 '21 at 09:01
  • try alert instead of console, this should make thing easer to confirm – Alen.Toma Dec 08 '21 at 23:05