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?
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')
);
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With