React: How to inject React component into 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 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>