AppProvider

Overview

The AppProvider component is a React context provider that manages and shares the application’s state and configurations across the app. It is a foundational component used in the root layout of the Next.js project and provides essential features such as translation handling, layout direction (LTR/RTL), and theme application.

Props

  • children (React.ReactNode): The child components to be rendered within the provider.

  • translation (Record<string, string>): The translation object to be used for internationalization.

Context

The AppProvider creates a context using AppContext, making the state and utility functions available throughout the application.

Context Value (AppContextType)

  • direction (string): Current text direction.

  • translation (Record<string, string>): Current translation data.

  • setDirection (function): Function to update the direction state.

Theme Integration

The AppProvider uses the WieldyTheme component to apply the default theme to the application. The theme is imported from the project’s configuration:

<WieldyTheme theme={config.defaultTheme}>{children}</WieldyTheme>

Hooks

useApp

The useApp hook provides access to the AppContext.

Example Usage

import { useApp } from "@/_components/AppProvider/hooks";

function MyComponent() {
  const { direction, setDirection } = useApp();

  return (
    <div>
      <p>Current Direction: {direction}</p>
      <button onClick={() => setDirection("rtl")}>Switch to RTL</button>
    </div>
  );
}

useTranslation

The useTranslation hook simplifies fetching translated strings based on keys.

Example Usage

import { useTranslation } from "@/_components/AppProvider/hooks";

function WelcomeMessage() {
  const t = useTranslation();

  return <p>{t("menu.dashboards")}</p>;
}

Details

The useTranslation hook retrieves nested keys from the translation object. If a key is not found, it logs an error and returns the key itself as a fallback.

Key Features

  1. Translation Support: Enables dynamic language changes by providing translations through the context.

  2. Direction Handling: Supports both LTR and RTL layouts, making it suitable for international applications.

  3. Theming: Integrates with the Wieldy theme system to apply consistent styles across the application.

Summary

The AppProvider component is a core utility in the Next.js project, encapsulating the app’s state and providing essential configurations such as translation, directionality, and theming. By using this component, developers can ensure consistency and scalability across the app.

Last updated