Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a value to bundled React JS file?

I wonder if it is possible to pass an argument to a react entry point.

My entry point looks like this:

module.exports = {
    entry: "./js/components/Application.js",
    output: {
        path: "./dist",
        filename: "bundle.js"
    },
    // ...
}

My Application.js:

import React from 'react';
import ReactDOM from 'react-dom';
import AnotherComponent from './AnotherComponent';

ReactDOM.render(<AnotherComponent />, document.getElementById('content'));

Not I bundle my application with webpack and include this bundle in another application. This application provides a div with id "content":

<body>
    <div id="content"></div>
    <script src="bundle.js" />
</body>

I know that I can do something like

<script src="bundle.js" myargument="somevalue" />

but how can I get this value for passing it to the react component AnotherComponent as a property?

like image 688
Ria Avatar asked Nov 10 '16 07:11

Ria


2 Answers

What about

<script id="bundle" src="bundle.js" myargument="somevalue" />

and then

const myScript = document.getElementById('bundle');

ReactDOM.render(<AnotherComponent 
   myArgument = {myScript.getAttribute('myargument')}
/>, document.getElementById('content')

);
like image 192
Lyubomir Avatar answered Oct 18 '22 04:10

Lyubomir


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>
like image 21
Krupal Patel Avatar answered Oct 18 '22 04:10

Krupal Patel