How to Call React Code from Outside React

Dec 18, 2019

2 min read

As you start writing more in React, it's easy to lose sight of how to do things "outside" of React.

For example, if you had a React modal prompting the user to log in, but you wanted to be able to "trigger" that modal from some separate Javascript (maybe from a script tag added by an outside source), how would you do that?

You might get caught up in a React-sounding solution:

1function App() {
2 function openModal() {
3 // ...other code to open modal
4 }
6 useEffect(() => {
7 // whenever openModal changes, you can bind it to the window?
8 window.openModal = openModal;
9 }, [openModal])
11 // ... rest of the component

And while this might work in some simpler cases, we're putting a function in the global scope and it's likely that we'll run into bugs if certain things change.

Instead, we should reach for a Javascript feature designed for situations like this: Custom Events.

When breaking down this problem, there are two main parts:

  • We want our app to "listen" and respond to an outside event
  • Code outside our app must be able to "trigger" this listener

If this sounds familiar, it's because we use the same Observer Pattern for HTML elements:

2 <button>Alert!</button>
3 <script>
4 const button = document.querySelector('#button');
6 // we add our listener here, and the "click" event is our trigger
7 button.addEventListener('click', () => {
8 // when the even is triggered, we run this code
9 alert('Button Clicked!');
10 });
11 </script>