Ria Ria - 26 days ago 12
React JSX Question

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?

leo leo
Answer

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

);
Comments