Ria
Ria

Reputation: 2090

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?

Upvotes: 5

Views: 3338

Answers (2)

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: 1

Lyubomir
Lyubomir

Reputation: 20027

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')

);

Upvotes: 4

Related Questions