6

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.

4
  • Is there a reason why you need to call a React component from a function? Can you provide the use case because the pattern doesn't seem correct and there's probably a better pattern for the use case Commented Mar 7, 2019 at 9:50
  • delete method is in react component. I'm working on click event in javascript function that need to call that delete method from react component. Commented Mar 7, 2019 at 9:51
  • What do you mean in javascript? you mean node? This doesnt sound like a good way of doing this. Commented Mar 7, 2019 at 9:54
  • 1
    Can you provide example code? To give context that will make it easier to understand the use case Commented Mar 7, 2019 at 9:55

1 Answer 1

8

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.