React - HOC vs utils functions

Viewed 190

Imagine two components in an app, both are different, but share a common functionality: "Open the iOS/Google Maps with a given location".

I have implemented the following method for doing that.

  const openGPS = (
    locationName,
    latitude = undefined,
    longitude = undefined
  ) => {
    const scheme = Platform.select({
      ios: "maps:0,0?q=",
      android: "geo:0,0?q=",
    });

    const latLng = `${latitude},${longitude}`;

    const url = Platform.select({
      ios: `${scheme}${locationName}@${latLng}`,
      android: `${scheme}${latLng}(${locationName})`,
    });

    Linking.openURL(url);
  };

But now my mind is scratched. I do not know where it is more correct to write it, if in a HOC "withOpenGPS", or in a separate module "maps.js", as an util function. Since this function uses APIs of react-native.

What do you think? It doesn't matter? Any principle to solve this type of ambiguous situation?

HOC:

const withOpenGPS = (Component) => (props) => {
  const openGPS = (
    locationName,
    latitude = undefined,
    longitude = undefined
  ) => {
    const scheme = Platform.select({
      ios: "maps:0,0?q=",
      android: "geo:0,0?q=",
    });

    const latLng = `${latitude},${longitude}`;

    const url = Platform.select({
      ios: `${scheme}${locationName}@${latLng}`,
      android: `${scheme}${latLng}(${locationName})`,
    });

    Linking.openURL(url);
  };

  return <Component {...props} openGPS={openGPS} />;
};

Util Function:

  export const openGPS = (
    locationName,
    latitude = undefined,
    longitude = undefined
  ) => {
    const scheme = Platform.select({
      ios: "maps:0,0?q=",
      android: "geo:0,0?q=",
    });

    const latLng = `${latitude},${longitude}`;

    const url = Platform.select({
      ios: `${scheme}${locationName}@${latLng}`,
      android: `${scheme}${latLng}(${locationName})`,
    });

    Linking.openURL(url);
};
1 Answers

You should go with Util that makes sense because this is an independent function that performs specific task. Its not like it depends on some component state or serve a purpose of a React Component that we basically use for rendering html elements on web page.

Related