Reputation: 563
I have one question because I'm not sure if that possible. I have ReactJS project that included some javascript functions.
I found solution to call javascript function from react components with window object but is it possible to call function from reactcomponents in javascript script?
For example I have definied function in React component. Is it possible to call that function in javascript?
Thank you.
Upvotes: 6
Views: 6018
Reputation: 222334
A function that is supposed to be used outside React application bundle should be exposed to global scope:
window.foo = () => { /* ... */ };
Then it can be accessed as such:
<script src="react-app-bundle.js"></script>
<script>
foo();
</script>
In case React application bundle is published as UMD module, it can export a function in entry point:
export const foo = () => { /* ... */ };
its namespace will be exposed to global scope when it's loaded via <script>
:
<script src="react-app-bundle.js"></script>
<script>
ReactAppNamespace.foo();
</script>
This is the case for a lot of third-party React libraries, React itself exposes React
global.
It's preferable to put all code that depends on React application internals to the application itself, so accessing globals is not needed.
Upvotes: 8