Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
23
rated 0 times [  28] [ 5]  / answers: 1 / hits: 20356  / 6 Years ago, mon, may 28, 2018, 12:00:00

I have a React component that I want to inject into the DOM. This is because my JS will be loaded through a script tag by other website owners, not loaded onto a SPA under my control.



What I want to do is append my Root component into the body of the webpage.



If I do something like this, then it replaces all the contents of my body, which is not what I want.



import React from react;
import ReactDOM from react-dom;

class Root extends React.Component {
render() {
return <div>heyyyyyyy</div>;
}
}

if (!module.parent) {
ReactDOM.render(<Root />, document.querySelector(body)); // <-- wrong
}


I want something like document.querySelector(body).appendChild(<Root />). Is this possible?


More From » reactjs

 Answers
21

If you opt for a one-liner :



ReactDOM.render(
<Root />,
document.body.appendChild(document.createElement(DIV))
)





Running Example:





class Root extends React.Component {
render() {
return <div>It works!</div>;
}
}

ReactDOM.render(
<Root />,
document.body.appendChild(document.createElement(DIV))
)

<script src=https://cdnjs.cloudflare.com/ajax/libs/react/16.0.0/umd/react.production.min.js></script>
<script src=https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.0.0/umd/react-dom.production.min.js></script>

<body></body>




[#54328] Thursday, May 24, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
andreguym

Total Points: 125
Total Questions: 112
Total Answers: 103

Location: Wallis and Futuna
Member since Tue, Mar 30, 2021
3 Years ago
;