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 modal4 }56 useEffect(() => {7 // whenever openModal changes, you can bind it to the window?8 window.openModal = openModal;9 }, [openModal])1011 // ... rest of the component12}
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:
1<body>2 <button>Alert!</button>3 <script>4 const button = document.querySelector('#button');56 // we add our listener here, and the "click" event is our trigger7 button.addEventListener('click', () => {8 // when the even is triggered, we run this code9 alert('Button Clicked!');10 });11 </script>12</body>
https://codesandbox.io/s/custom-events-m95t5?view=split&fontsize=12