Search code examples
reactjsmaterial-uilocalizationmaterial-designtsx

Export helper functions with Material-UI theme support


I want to create a new file that will contain helper functions for several components that using the same logic, The issue is that I need to use my locale.ts file in that file for using the current language according to the theme (localization) but it seems I can't call const t: any = useTheme().props in ts file. (error: React Hook "useTheme" cannot be called at the top level. React Hooks must be called in a React function component or a custom React Hook function)

today in my tsx component files:

t: any = useTheme().props
t.General.someString

How can I use localization of the Material-UI theme in my helper functions file?


Solution

  • Hook cannot be used at the top level, this is unsupported:

    // top level
    const any = useTheme().props;
    

    It's supposed to be used inside a functional component or another hook. For reference, see the rules of hook here:

    function Component() {
      // valid because it's inside a React function
      const any = useTheme().props;
      return (...);
    }
    

    What you can do is create a helper hook that returns a specific data that you need:

    const useThemeProps = () => {
      // valid because it's inside another hook
      return useTheme().props;
    }
    
    function Component() {
      const any = useThemeProps();
      return (...);
    }
    

    You can also just return the data directly:

    function Component() {
      const { props } = useTheme();
      return (...);
    }