PolygotDocumentation
React translation library with intelligent context management and automatic content translation.
Installation
npm install polygot
Quick Start Example
This example demonstrates how to use `PolygotProvider`, `usePolygot`, `Polygot`, and `NoPolygot` components to manage translations and prevent translation for specific content.
import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { NoPolygot, Polygot, usePolygot } from 'polygot';
// --- Mock API Call ---
// This function simulates fetching data from a server.
// It returns a Promise that resolves with some data after a 1.5-second delay.
const mockApiCall = () => {
console.log("Fetching data from API...");
return new Promise((resolve) => {
setTimeout(() => {
const data = {
title: "Welcome to the Dashboard",
description: "This content was loaded from a remote API and is ready for translation.",
};
console.log("Data fetched successfully:", data);
resolve(data);
}, 1500);
});
;
function App() {
const { language, setLanguage } = usePolygot();
const router = useRouter();
// State to hold the data fetched from the API
const [apiData, setApiData] = useState(null);
// State to manage the loading status
const [isLoading, setIsLoading] = useState(true);
// useEffect hook to call the API when the component mounts
useEffect(() => {
setLanguage("ar")
// We don't want to refetch data when the language changes,
// so we use an empty dependency array [].
setIsLoading(true);
mockApiCall().then(data => {
setApiData(data);
}).catch(error => {
console.error("Failed to fetch API data:", error);
// You could set an error state here as well
}).finally(() => {
setIsLoading(false);
});
}, []); // <-- Empty dependency array means this runs only once on mount
// Function to toggle between English and French
const toggleLanguage = () => {
const newLanguage = language === 'en' ? 'fr' : 'en';
setLanguage(newLanguage);
};
return (
<div className="p-8 font-sans text-center">
<Polygot>
<div>
<p className="mb-4">
Current Language: <strong className="text-emerald-600">{language}</strong>
</p>
<div className="border border-gray-200 p-4 rounded-lg my-8 shadow-sm">
{isLoading ? (<p>Loading API data...</p>) : ( apiData && (<div>
<h2 className="text-2xl font-bold text-gray-900 mb-2">{apiData.title}</h2>
<p className="text-gray-700">{apiData.description}</p>
</div>
)}
</div>
<button onClick={toggleLanguage} className="mb-4">
Click to toggle language</button>
</div>
</Polygot>
<NoPolygot>
<div>
<p className="text-gray-500 mt-8">
This part is wrapped in 'NoPolygot' and will not be translated.</p>
<button onClick={() => router.push("/two")} className="mt-4">
Navigate to Page Two</button>
</div>
</NoPolygot>
</div>
};
export default App;