Ankur
Ankur

Reputation: 102

How to send value in bundled ReactJs

I'm working on the ReactJs project where we aren't using any API to manage data.

In the project we use Webpack to bundle React APP.

Now issue is the React APP is should be useable on any website by including the bundle.js and website will allow to give some input data and accordingly we will load the ReactAPP.

So, I'm finding the best way to send data into bundled ReactAPP so we can write our logic to load React based on provided Data.

Note: There is no chance to use API call as ReactAPP is independent to use on any website by including bundle.js

In PHP Website

index.php

<script type="text/javascript">
const configReactApp = {
   "selector": "loadmy_react_here", //should ID
   "config": {}
};
</script>

<!--- My React APP bundled js using Webpack --->
<script src="bundled.min.js"></script>

<body>
   <div class="container">
      <div class="left-panel"></div>
      <div class="right-panel">
        <div id="loadmy_react_here">
         <!-- Load my react app here --->
        </div>
      </div>
   </div>
</body>

In React

ReactDOM.render(<DashboardComponent 
   myArgument = {configReactApp.config}
/>, document.getElementById(configReactApp.selector)

);

Upvotes: 2

Views: 394

Answers (1)

Krupal Patel
Krupal Patel

Reputation: 1497

In ReactJS file src/index.js

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

window.MyReactApp = {
    init: (selector, myData) => {
        selector = selector.substring(1);
        const renderComponent = (<homeComponent mydata={myData} />);
        ReactDOM.render(renderComponent, document.getElementById(selector));
    },
};

Now load the ReactJs App where you want to load.

<script type="text/javascript" src="bundle.min.js"></script>
<div id="load-myreactapp"></div>

<script type="text/javascript">
    const myData = {};
    MyReactApp.init('#load-myreactapp', myData);
</script>

Upvotes: 2

Related Questions