Return values from event handlers

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the javascript category.

Last Updated: 2024-03-05

The return value of an event handler determines whether or not the default browser behaviour should take place as well. In the case of clicking on links, this would be following the link, but the difference is most noticeable in form submit handlers, where you can cancel a form submission if the user has made a mistake entering the information.

Background ([source])[https://www.permadi.com/tutorial/jsEventBubbling/index.html]) Returning false tells the default event handler to be skipped. Returning true tells the event-chain to continue (meaning the default event handler will be called). If no return value is specified, true is assumed.

Event handler that didn't return true failed to work

  useEffect(() => {
    BackHandler.addEventListener("hardwareBackPress", handleBackButtonPress);
    return () => {
      BackHandler.removeEventListener(
        "hardwareBackPress",
        handleBackButtonPress
      );
    };
  }, []);

  const handleBackButtonPress = () => {
    try {
      webviewRef.current?.goBack();
      return true; // keep things going
    } catch (error) {
      console.error("[handleBackButtonPress] Error : ", error.message);
      return false
    }
  };

Resources

https://stackoverflow.com/questions/128923/whats-the-effect-of-adding-return-false-to-a-click-event-listener