Mohamad Alasly
Mohamad Alasly

Reputation: 340

how to render react component to another web app

i have a webapp bulid on react.js ! with many components ! so i want to give other website some service !

other website should include a js file from my webapp ! for example :

<script type="text/javascript" src="https://mywebsite/script.js"></script>
//here am calling buttons from my js file
<script type="text/javascript">
    buttons.render("root");
</script>

and my app that based bulid on react should render buttons !

in normal js it will be like this

class buttons{
  constructor() {

  }
  render (id){
    document.getElementById(id).innerHTML = "here is buttons";
  }
}

buttons= new buttons();

but i don't have any idea how i should do that in react , i want to do it with react because i have some logic to do !

Upvotes: 3

Views: 991

Answers (1)

Sagiv b.g
Sagiv b.g

Reputation: 31024

You can take advantage of ReactDOM.render and expose it as a global API of your Component.

The fact that ReactDOM.render will re-render the component when receiving new props can help a lot here.

window.MyComponent = {
    mount: (props, container) => {
        ReactDOM.render(<MyComponent {...props} />, container);
    },
    unmount: (container) => {
        ReactDOM.unmountComponentAtNode(container);
    }
}

Your consumers can then use this API to mount or update and unmount the component

I wrote about this in more details on my blog, hope it helps.

Upvotes: 1

Related Questions