In this blog, weโll walk through building a Flag Country Finder App using React, the Tolgee localization library, and REST Countries API. This app allows users to browse countries, change languages dynamically, and display country details along with flags. The Tolgee library simplifies localization by making translation handling seamless.
Here is the Demo : https://tolgee-flag-finder.netlify.app/
Letโs dive into the code to understand how each piece contributes to the app!
What is Tolgee?
Tolgee is a powerful, easy-to-use localization platform that integrates with your frontend applications. It enables:
- Dynamic translation switching at runtime.
- Simple formatting for placeholders and values.
- Real-time UI translation with DevTools.
- API integration for more flexible translation backends.
In our example, Tolgee enhances the user experience by supporting multiple languages: English, Hindi, Russian, Chinese, and Spanish.
Code Walkthrough
1. Project Setup
This app is built with React and uses Axios to fetch country data from the REST Countries API. Additionally, we configure Tolgee to manage language translations dynamically.
Dependencies:
npm install react axios @tolgee/react
## 2. **Tolgee Initialization**
Hereโs the key part of setting up Tolgee in our app. We initialize Tolgee by providing an **API key** and backend configuration.
javascript
const tolgee = Tolgee()
.use(DevTools())
.use(FormatSimple())
.use(BackendFetch({
prefix: 'https://cdn.tolg.ee/1c78a2bfe00648ecc5bcd10aa4c320ae'
}))
.init({
language: "en",
apiUrl: import.meta.env.VITE_APP_TOLGEE_API_URL,
apiKey: import.meta.env.VITE_APP_TOLGEE_API_KEY,
});
3. Fetching Country Data with Axios
The useEffect hook fetches all countries and sorts them by name. The data is stored in the countries state.
javascript
Copy code
useEffect(() => {
axios.get("https://restcountries.com/v3.1/all")
.then((response) => {
const sortedCountries = response.data.sort((a, b) =>
a.name.common.localeCompare(b.name.common)
);
setCountries(sortedCountries);
})
.catch((error) => console.error("Error fetching countries:", error));
}, []);
4. Creating the UI with Language Selectors and Dropdowns
The country selector and language switcher are key UI components. Using <select> elements, we allow users to switch between languages or pick a country.
javascript
Copy code
<select
onChange={(e) => tolgee.changeLanguage(e.target.value)}
value={tolgee.getLanguage()}
>
<option value="en">๐ฌ๐ง English</option>
<option value="hi">๐ฎ๐ณ Hindi</option>
<option value="es">๐ช๐ธ Spanish</option>
<option value="ru-RU">๐ท๐บ Russian</option>
<option value="zh">๐จ๐ณ Chinese</option>
</select>
The TolgeeHelper function updates the selected country when a user makes a choice from the dropdown.
5. Using Translations with the <T> Component
The <T> component from Tolgee makes translation insertion easy. Hereโs how we display country information with localized labels:
javascript
Copy code
<p>
<strong><T keyName="capkey" defaultValue="Capital" />:</strong>
{selectedCountry.capital ? selectedCountry.capital[0] : "N/A"}
</p>
<p>
<strong><T keyName="popkey" defaultValue="Population" />:</strong>
{selectedCountry.population.toLocaleString()}
</p>
<p>
<strong><T keyName="regkey" defaultValue="Region" />:</strong>
{selectedCountry.region}
</p>
If the keys (capkey, popkey, regkey) are not available in the selected language, Tolgee falls back to the defaultValue.
6. Complete App Component
Hereโs the full App component:
javascript
Copy code
const App = () => {
const [countries, setCountries] = useState([]);
const [selectedCountry, setSelectedCountry] = useState(null);
useEffect(() => {
axios.get("https://restcountries.com/v3.1/all")
.then((response) => {
const sortedCountries = response.data.sort((a, b) =>
a.name.common.localeCompare(b.name.common)
);
setCountries(sortedCountries);
})
.catch((error) => console.error("Error fetching countries:", error));
}, []);
const TolgeeHelper = (event) => {
const country = countries.find(c => c.cca2 === event.target.value);
setSelectedCountry(country);
};
return (
<TolgeeProvider tolgee={tolgee} fallback="Loading...">
<div style={styles.container}>
<h1 style={styles.title}>Flag Country Finder ๐</h1>
<div style={styles.selectorContainer}>
<select
onChange={(e) => tolgee.changeLanguage(e.target.value)}
value={tolgee.getLanguage()}
>
<option value="en">๐ฌ๐ง English</option>
<option value="hi">๐ฎ๐ณ Hindi</option>
<option value="es">๐ช๐ธ Spanish</option>
<option value="ru-RU">๐ท๐บ Russian</option>
<option value="zh">๐จ๐ณ Chinese</option>
</select>
<select onChange={TolgeeHelper} defaultValue="">
<option value="" disabled>Select a country</option>
{countries.map((country) => (
<option key={country.cca2} value={country.cca2}>
{country.name.common}
</option>
))}
</select>
</div>
{selectedCountry && (
<div style={styles.countryInfo}>
<h2 style={styles.countryName}>{selectedCountry.name.common}</h2>
<img
src={selectedCountry.flags.png}
alt="Flag"
style={styles.flag}
/>
<p>
<strong><T keyName="capkey" defaultValue="Capital" />:</strong>
{selectedCountry.capital ? selectedCountry.capital[0] : "N/A"}
</p>
<p>
<strong><T keyName="popkey" defaultValue="Population" />:</strong>
{selectedCountry.population.toLocaleString()}
</p>
<p>
<strong><T keyName="regkey" defaultValue="Region" />:</strong>
{selectedCountry.region}
</p>
</div>
)}
</div>
</TolgeeProvider>
);
};
7. Styling the App
We use simple CSS-in-JS styling to make the UI visually appealing:
javascript
Copy code
const styles = {
container: {
display: "flex",
flexDirection: "column",
alignItems: "center",
height: "100vh",
background: "linear-gradient(135deg, #1f1c2c, #928dab)",
color: "#fff",
},
// Additional styles...
};
Conclusion
Using Tolgee makes it easy to manage translations in your React app. With just a few lines of code, you can dynamically switch languages and enhance the app's usability for users worldwide. Paired with the REST Countries API, weโve built a visually appealing Flag Country Finder App that is intuitive and multilingual.
Feel free to customize the translations or experiment with additional languages. ๐
Give Tolgee a try in your next project, and enjoy a smooth localization experience! ๐
Top comments (1)
Great, project! Thanks a lot for contributing with this Tolgee demo