🔧 Building a Multilingual Country Finder App with Tolgee and React 🌍
Nachrichtenbereich: 🔧 Programmierung
🔗 Quelle: dev.to
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.vercel.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! 🚀
...
🔧 Building a Lyrics Finder App with React
📈 27.24 Punkte
🔧 Programmierung
🔧 Building a Crypto Finder App with React
📈 27.24 Punkte
🔧 Programmierung
🔧 Weather App with Tolgee
📈 27.19 Punkte
🔧 Programmierung
🔧 Weather App with Tolgee
📈 27.19 Punkte
🔧 Programmierung
🔧 Building Recipe Finder Website using React
📈 24.66 Punkte
🔧 Programmierung
🔧 Building a Movie Finder Website using React
📈 24.66 Punkte
🔧 Programmierung
🔧 Random Recipe Generator with Tolgee
📈 24.61 Punkte
🔧 Programmierung