Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React: How to inject React component into body?

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?

like image 748
bigpotato Avatar asked May 28 '18 20:05

bigpotato


People also ask

What is ReactDOM in React?

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.

Can you use React components in HTML?

Simply adding React components into HTML code is not possible, because <MyComponent></MyComponent> is not HTML at all, it is JSX.


2 Answers

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>
like image 51
alegria Avatar answered Oct 16 '22 21:10

alegria


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>
like image 2
Damon Avatar answered Oct 16 '22 21:10

Damon