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 :)

4
  • Try using dangerouslySetInnerHTML stackoverflow.com/questions/23616226/… Commented Dec 5, 2021 at 10:52
  • That's the solution I'm currently using. However, the JS is not executed. Commented Dec 5, 2021 at 11:24
  • can you add the HTML and CSS responses in the question as well Commented Dec 5, 2021 at 13:07
  • The problem lies within the JS code not being executed. At list I think the parent divs render properly. Commented Dec 6, 2021 at 13:50

1 Answer 1

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>
)

Sign up to request clarification or add additional context in comments.

6 Comments

I'm using functional components within React Typecsript, I'm unable to do that.
I edited my answer and added a functional components. Have a look
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.
This should have worked, then it is something to do with your js file
For example. Your code injects the HTML correctly. But if I try to do something like this divElement.current.innerHTML = '<div><script>console.log("Hello world!")</script></div>'; 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?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.