Lädt...


🔧 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 Multilingual Country Finder App with Tolgee and React 🌍


📈 80.58 Punkte
🔧 Programmierung

🔧 Building a Country-to-Flag Emoji Converter App with Vite, TypeScript, and Tolgee


📈 46.46 Punkte
🔧 Programmierung

🔧 Building a Fun Workout App with React, Vite, and Tolgee


📈 40.52 Punkte
🔧 Programmierung

🔧 Creating a Multilingual Expense Tracker with Tolgee


📈 40.1 Punkte
🔧 Programmierung

🔧 Building a Stylish Expense Tracker with React, SVG Pie Charts, and the Tolgee Platform


📈 37.93 Punkte
🔧 Programmierung

🔧 Building a Country Finder Application with React


📈 36.59 Punkte
🔧 Programmierung

🔧 How to Build a Weather Forecast App with React, TypeScript, Tolgee and OpenWeather API


📈 34.49 Punkte
🔧 Programmierung

🔧 "Zenith" – A Serene Meditation App with React, Tolgee, and Tailwind CSS


📈 34.49 Punkte
🔧 Programmierung

🔧 Creating a Dream Recorder using React, Vite, and Tolgee 😀🐁


📈 31.9 Punkte
🔧 Programmierung

🔧 Webinar: From multilingual UI to multilingual company


📈 30.98 Punkte
🔧 Programmierung

📰 Microsoft Introduces Multilingual E5 Text Embedding: A Step Towards Multilingual Processing Excellence


📈 30.98 Punkte
🔧 AI Nachrichten

🔧 Building a simple Full-Stack Restaurant Finder App with React, Redux, Node.js, and Google Places API


📈 28.55 Punkte
🔧 Programmierung

🔧 Building CRUD App with react-form, zod, react data grid, react-query and json-server


📈 27.88 Punkte
🔧 Programmierung

📰 WiFi Finder, a Popular Hotspot Finder App, Exposed 2 Million Wi-Fi Network Passwords


📈 27.87 Punkte
📰 IT Security Nachrichten

📰 WiFi Finder, a Popular Hotspot Finder App, Exposed 2 Million Wi-Fi Network Passwords


📈 27.87 Punkte
📰 IT Security Nachrichten

🔧 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

🍏 Duplicate File Finder Remover 7.0.5 - Professional duplicate finder and cleaner.


📈 26.59 Punkte
🍏 iOS / Mac OS

🔧 This week's API summary round-up: Vessel Info, Vessel Finder and port finder


📈 26.59 Punkte
🔧 Programmierung

🔧 Translate & Guess: Build a Flag Quiz with Expo and Tolgee


📈 25.92 Punkte
🔧 Programmierung

📰 Okadminfinder3 - Admin Panel Finder / Admin Login Page Finder


📈 25.28 Punkte
📰 IT Security Nachrichten

📰 OKadminFinder - Admin Panel Finder / Admin Login Page Finder


📈 25.28 Punkte
📰 IT Security Nachrichten

🍏 Finder Windows 1.5.2 - Access macOS Finder windows easily.


📈 25.28 Punkte
🍏 iOS / Mac OS

🍏 Path Finder 2151 - Powerful, award-winning Finder alternative.


📈 25.28 Punkte
🍏 iOS / Mac OS

🔧 Building Recipe Finder Website using React


📈 24.66 Punkte
🔧 Programmierung

🔧 Building a Movie Finder Website using React


📈 24.66 Punkte
🔧 Programmierung

🔧 Unveiling DishHub - A Culinary Journey with Tolgee


📈 24.61 Punkte
🔧 Programmierung

🔧 Random Recipe Generator with Tolgee


📈 24.61 Punkte
🔧 Programmierung

matomo