React Usage

UrduMagic provides first-class React support via the urdumagic/react package with pre-built hooks and context providers.

Using useUrduMagic

Import useUrduMagic directly from urdumagic/react:

tsx
import { useUrduMagic } from 'urdumagic/react';

export function LanguageDemo() {
  const { 
    currentLanguage, 
    switchLang, 
    translate, 
    toUrdu, 
    toRoman, 
    isTranslating 
  } = useUrduMagic({
    defaultLang: 'en',
    modes: ['en', 'ur', 'roman'],
    showSwitcher: false, // Use our own custom UI buttons
  });

  return (
    <div className="p-6 border rounded-xl space-y-4">
      <p className="text-sm text-gray-500">
        Current Language: <span className="font-bold text-blue-600">{currentLanguage}</span>
      </p>

      <div className="flex gap-2">
        <button 
          onClick={() => switchLang('ur')} 
          className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition"
        >
          اردو (Urdu)
        </button>
        <button 
          onClick={() => switchLang('roman')} 
          className="px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-50 transition"
        >
          Roman Urdu
        </button>
        <button 
          onClick={() => switchLang('en')} 
          className="px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-50 transition"
        >
          English
        </button>
      </div>

      {isTranslating && <p className="text-xs text-blue-500">Updating page...</p>}
    </div>
  );
}

App-Wide Context with UrduMagicProvider

For applications with multiple components needing access to language state and translation functions, wrap your root component with UrduMagicProvider:

tsx
import { UrduMagicProvider, useUrduMagicContext } from 'urdumagic/react';

// 1. Wrap your root application
export function App() {
  return (
    <UrduMagicProvider config={{ defaultLang: 'en', modes: ['en', 'ur', 'roman'] }}>
      <Navbar />
      <MainContent />
    </UrduMagicProvider>
  );
}

// 2. Consume from any child component
export function Navbar() {
  const { currentLanguage, switchLang } = useUrduMagicContext();

  return (
    <nav className="flex justify-between items-center p-4 border-b">
      <span>My Website</span>
      <select 
        value={currentLanguage} 
        onChange={(e) => switchLang(e.target.value as any)}
        className="px-3 py-1.5 border rounded-md"
      >
        <option value="en">English</option>
        <option value="ur">اردو</option>
        <option value="roman">Roman</option>
      </select>
    </nav>
  );
}