0

I am trying to insert ajax response to body from page that has React JS.

The page has only div and script tag like below;

<div data-react-class="example" data-react-props="{}" data-react-cache-id="example-0" class="example"></div>
<script type="text/javascript" src="/packs/js/application.js"></script>

I tried document.body.append, document.write, document.body.innerHTML +=... or insert div and script separately but React Component not initialized. All methods I tried that inserting code but React JS not activated.

I tried setTimeout for script but nothing changed. Although when I open the page without ajax it works as I expected.

What am I missing?

How can I initialize React JS after insert to page with javascript.

Code Example: https://codesandbox.io/embed/awesome-roentgen-q9m0b

Works without ajax: https://q9m0b.csb.app/src/get-ajax-page.html

But does not initialize if I insert with ajax: https://q9m0b.csb.app/

1 Answer 1

0

You will need to do document.body.innerHTML+=(<your ajax response>). I have added a mock version of what you are trying to achieve. The div is rendering fine using this code

https://codesandbox.io/s/react-playground-forked-h5g57?file=/index.js

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

3 Comments

I created an example for you. This is react page working: q9m0b.csb.app/src/get-ajax-page.html and this page is index.html inserting with ajax: q9m0b.csb.app can you fix this usage?
First of all I would suggest you to add your approach to the original question as it is not clear from the question itself what you are trying to do. The second thing is that you can not just insert ES6 module file(react-components.js) directly to your html file. This files are actually compiled and converted to plain js when you build your React file. So your react-components.js must be in plain js to achieve the desired affect. So write your file in plain js and modify the approach
My own javascript file compiled with webpacker. This is not a problem. I don't know codesandbox.io how works. I tried to create an example similar to my problem.

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.