Go to main content
Development/Frontend

Elog: Event Bubbling

by Nyangbari 2024. 5. 2.

When I first started my journey as a frontend developer, our team was tasked with building an mobile app for Bitcoin L2 wallet.

 

💥 Issue

In our React Native application, I was working on the ConnectEmailPage. Here’s the relevant part of the code:

const ConnectEmailPage = observer(({ navigation, route }: any) => {
 ...
 return (
  <KeyboardAwareScrollView scrollEnabled={isKeyboardVisible} ref={scrollView}>
    <View
      onTouchEnd={() => {Keyboard.dismiss();}}
    >
      <View>
        ...
          <TextInput
            value={email}
            ...
          />
        ...
      </View>
    </View>
  </KeyboardAwareScrollView>
 )

So, when you tap on the TextInput, the keyboard pops up as it should. Then, my intention was for the keyboard to disappear whenever the user tapped anywhere outside the TextInput field. So my initial approach was to use onTouchEnd={() => { Keyboard.dismiss(); }} at the top of the View component, but it did not behave as expected.

 

🤔 Cause

The culprit, I discovered, was ‘Event Bubbling.’ In web and mobile development, event bubbling is a process where an event first triggers on the deepest possible component and then fires sequentially up to the parent components, all the way to the root.

So back to our case, when the TextInput is pressed, the keyboard appears as a result of an event. This event then bubbles up 🫧bubble, bubble🫧 to the parent component. During this process, there’s a conflict between the event that opens the keyboard and the event that closes it. Since the TextInput remains focused, the keyboard stays open. This is why the keyboard does not close as intended.

 

💡 Solution

The solution was simple; By implementing e.stopPropagation() in the TextInput component, I could effectively prevent the event from bubbling up:

<TextInput
 value={email}
 ...
 onTouchEnd={(e) => e.stopPropagation();}}
/>

This change ensures that tapping on the TextInput doesn’t trigger the onTouchEnd event of the parent View, thereby keeping the focus state clear and the behavior predictable.

I had previously learned about event bubbling, but encountering it in a real-world scenario was a different challenge altogether. It took some time to identify the cause, but once I did, it provided a clear insight into how deeply interconnected components and events are in React Native.
This experience was a great reminder of the importance of understanding the fundamentals of event handling!