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?
The react-dom package provides DOM-specific methods that can be used at the top level of your app and as an escape hatch to get outside the React model if you need to.
Simply adding React components into HTML code is not possible, because <MyComponent></MyComponent> is not HTML at all, it is JSX.
If you opt for a one-liner :
ReactDOM.render(
<Root />,
document.body.appendChild(document.createElement("DIV"))
)
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>
Create the root element and append it to the DOM yourself
const rootEl = document.createElement('div')
document.body.appendChild(rootEl)
class Root extends React.Component {
render () {
return <div>heyyyyyyy</div>
}
}
ReactDOM.render(
<Root />,
rootEl
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div>don't replace me</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With