Im not sure if this has been asked before or anybody has encountered the same issue on reactjs. So the scenario is like this, I have an index.html file that includes some javascript. Now on my react component, I have a condition that will render only if the condition is true. This means that initially when my page loaded the component has not been rendered yet. When I toggle a button this is where that component gets rendered. That child component needs to call a javascript method that was included on my index.html. How should I do this?
Any help is greatly appreciated.
First, create a React project by typing inside the terminal. To execute a external JavaScript function, we need to put the name of the function “alertHello” inside the square bracket. If you click on the alert button, it should popup the alert “Hello”. This imply we can call the external JavaScript function from React.
To include an external JavaScript file, we can use the script tag with the attribute src . You've already used the src attribute when using images. The value for the src attribute should be the path to your JavaScript file. This script tag should be included between the <head> tags in your HTML document.
You separate all events into separated state and actions, and dispatch them from components. if you need to use function from the child in a parent component, you can wrap in a third component, and clone parent with augmented props.
In index.html
<script type="text/javascript"> function test(){ alert('Function from index.html'); } </script>
In your component
componentWillMount() { window.test(); }
Try this solution to call global functions from React with TypeScript enabled:
Either in index.html or some_site.js
function pass_function(){ alert('42'); }
Then, from your react component:
window["pass_function"]();
And, of course, you can pass a parameter:
//react window["passp"]("react ts"); //js function passp(someval) { alert(`passes parameter: ${someval}`); }
So either you define the method on global scope (aka window). And then you can use it from any methods, being React or not.
Or you can switch to module based paradigm and use require/import to get the module and use the function.
For bigger projects the latter is better as it's scales, while if you need a demo or POC you can certainly hook all to global scope and it will work.
More information about modules is at: http://exploringjs.com/es6/ch_modules.html
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