I have define a react component that receive parameters
import React from 'react';
import ReactDOM from 'react-dom/client';
import DocumentEditor from './DocumentEditor';
export default function DocumentEditorContainer(props){
//let props = {container : "root", value: ""};
const root = ReactDOM.createRoot(document.getElementById(props.container));
root.render(
<React.StrictMode>
<DocumentEditor value = {props.value}/>
</React.StrictMode>
);
}
I package it using webpack, and I need to call that module from a script tag inside a html file
<script type="text/javascript" src="./aux.js"></script>
<script>
DocumentEditorContainer("root", "123");
</script>
But I am getting that DocumentEditorContainer is undefined. What am I doing wrong?
>Solution :
From the code snippets you’ve shared, it seems like you’re trying to use the DocumentEditorContainer function from an external script in your HTML file. However, the problem is that this function isn’t globally accessible because it’s bundled with webpack.
When webpack bundles your code, it encapsulates your modules in closures, and thus they aren’t added to the global scope. As a result, when you try to call DocumentEditorContainer from your script tag, it’s undefined because it’s not in the global scope.
To solve this issue, you need to expose your DocumentEditorContainer to the global scope. I’ve never used it in a project, but I’ll give it a try, as I think it should work.
Basically, you can do this by attaching the function to the window object in your JavaScript file. Here’s how you can do it:
import React from 'react';
import ReactDOM from 'react-dom/client';
import DocumentEditor from './DocumentEditor';
function DocumentEditorContainer(props){
const root = ReactDOM.createRoot(document.getElementById(props.container));
root.render(
<React.StrictMode>
<DocumentEditor value = {props.value}/>
</React.StrictMode>
);
}
// Expose the function to the global scope
window.DocumentEditorContainer = DocumentEditorContainer;
Now, you should be able to call DocumentEditorContainer from your HTML file:
<script type="text/javascript" src="./aux.js"></script>
<script>
DocumentEditorContainer({container: "root", value: "123"});
</script>
Note that I changed the way DocumentEditorContainer is called. Instead of two arguments, it should be called with an object that has container and value properties, as that’s what your function expects.
Remember that attaching variables to the global scope can potentially lead to conflicts and should generally be avoided if possible. In a larger application or when integrating with other libraries, it would be better to manage all of your code within the React application and avoid manual DOM manipulations and global state.