skip to Main Content

I was given a task to implement a localization for the whole mobile app on react native with i18next, react localize.

There is a lot of text in many files and so far the only way is to do it manually. Search through the files and then replace the text with the corresponding t reference to the translation file.

Is there actually another way of doing it faster and more convenient?

I made changes in quite many files to the moment. Sometimes thinking if there is a better way to optimize this process.

2

Answers


  1. If by chance your original language isn’t English – You can search for characters in that language (using a regex). That will surface all the strings that are user facing (otherwise the code is in English).

    Aside from that, I think regex’s are your friend. You can search for ".*?" and similar to catch strings.

    If you already have a translation file, then you could write a simple script that pulls a translated string, searches for it in project source files, and replaces the occurence with the t() equivalent.

    Hope this helps 🙏🏻

    Login or Signup to reply.
  2. Almost all visible text (exceptions are placeholder and accessibilityLabels) would be in <Text> so you can probably override it with a higher-order component to use the existing text value looked up via i18n-next. It’s not perfect but it would be a start.

    This would do the reverse of what you want (in that it replaces text with i18n keys) https://github.com/trajano/spring-cloud-demo/blob/rework/expo-app/src/lib/native-unstyled/hoc/withI18n.tsx. But I used that along with my hoc template

    (note untested)

    import {
      ComponentType,
      forwardRef,
      NamedExoticComponent,
      PropsWithoutRef,
      ReactElement,
      Ref,
      RefAttributes,
    } from "react";
    
    export function withChildrenAsI18n<P extends Q, Q extends TextProps, T>(
      Component: ComponentType<Q>,
      _options?: O
    ): NamedExoticComponent<PropsWithoutRef<P> & RefAttributes<T>> {
      function useWrapped({children, ...rest}: P, ref: Ref<T>): ReactElement<Q> {
        const translatedChildren = t(children);
        const componentProps: Q = {...rest, children: translatedChildren } as Q;
        return <Component {...componentProps} ref={ref} />;
      }
      const displayName = Component.displayName ?? Component.name;
      useWrapped.displayName = `withChildrenAsI18n(${displayName})`;
      return forwardRef(useWrapped);
    }
    

    then add something like

    import {
      Text as RNText,
    } from "react-native";
    export const Text = withChildrenAsI18n(RNText);
    

    Then do a search and replace the text import with this replacement.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search