skip to Main Content

I implemented i18n into my app and i have a navbar data file, which is the data base for the page title and the tabs, i need to implement th i18n useTranslation(); into it and im not sure how.

here is an example of my implementation into the Navbar.js component:

import React, { useState, useEffect } from "react";
import { Link, useLocation } from "react-router-dom";
import { NavbarData } from "./NavbarData";
import { IconContext } from "react-icons";
import "./Navbar.css";
import Hamburger from "./Icons/Hamburger.svg";
import "./Icons/p_logo_color.png";
import Persona from "./Icons/Persona.svg";
import Logout from "./Icons/Logout.svg";







import { useTranslation } from 'react-i18next';








//Navbar function
function Navbar() {
  const [sidebar, setSidebar] = useState(false);
  const showSidebar = () => setSidebar(!sidebar);
  const [pageName, setPageName] = useState('Operational Overview');
  const location = useLocation();
  

  //i18n

  const { t, i18n } = useTranslation();
  const lngs = {
    en: {nativeName: 'English'},
    fr: {nativeName: 'French'}
  };
  
  

  

  const getPageTitleByUrl = (path) => {
    NavbarData.filter((navItem) => {
  
      if(navItem.path === path) {
        setPageName(navItem.title);
      }
      return (true)
    } )

  };

  const userConfigPageTitle = (path) => {
    setPageName("User Information");

  }

  

  useEffect(() => {
    if(location.pathname) {
      getPageTitleByUrl(location.pathname);
    }
  }, [location] ); 

  const handleLanguageChange = (e) => {
    i18n.changeLanguage(e.target.value);
  }
  

  return (
    <>
      <IconContext.Provider value={{ color: "undefined" }}>
        <div className="navbar">
          <Link to="#" className="menu-bars">
             <img src={Hamburger} alt="hamburger" onClick={showSidebar} />
          </Link>
          <div className="criminal-records">{t("navbar.criminalRecords")}</div> 

          <div className="pageTitle"><h1>{t(pageName)}</h1></div>

        <div className="language-component"> 
        <div>
          {Object.keys(lngs).map((lng) => (
            <button key={lng} style={{ fontWeight: i18n.resolvedLanguage === lng ? 'bold' : 'normal' }} type="submit" onClick={() => i18n.changeLanguage(lng)}>
              {lngs[lng].nativeName}
            </button>
          ))}
        </div>
       
          <select onChange={handleLanguageChange}
          value={localStorage.getItem("i18nextLng")}>
          <option value="en">English</option>
          <option value="fr">French</option>
          </select>
        
        
        

        </div>



          <Link to='userconfig' onClick={userConfigPageTitle}>
          <div><img className="userIcon" src={Persona} alt="persona" /> </div>
          <div className="userButton">User123#</div>
          </Link>
        
     
          <Link to='/' className="logout-button">
          <div className="right-side">
            <img className="logoutIcon" src={Logout} alt="persona" /> </div>
          <div className="logoutButton">{t("navbar.logout")}</div> 
          </Link>
        </div>
        <nav className={sidebar ? "nav-menu active" : "nav-menu"}>
          <ul className="nav-menu-items" onClick={showSidebar}>
        
            {NavbarData.map((item, index) => {
              return (
                <li key={index} className={item.cName}>
                  <Link to={item.path}>
        
                    <span className="navbutton-text" ><span className="navbutton-icon">{item.icon}</span>{item.title}</span>
                    
                    
                  </Link>
                  
                </li>
                
              );
            })}

          </ul>
        </nav>
      </IconContext.Provider>
    </>
  );
}

export default Navbar;

and this is the NavbarData.js:

import React from 'react'



import startpageIcon from './Icons/startpage.svg';
import performance from './Icons/performance.svg';
import fraud from './Icons/fraud.svg';
import { useTranslation } from 'react-i18next';



export const NavbarData = [
    {
        title: 'Operational Overview',
        path: '/monitoringoverview',
        icon: <img  src={startpageIcon} alt="" />,
        cName: 'nav-text'
    },
    {
        title: "Performance Quality",
        path: "/performancequality",
        icon: <img src={performance} alt="" />,
        cName: 'nav-text'
    },

    {
        title: "Fraud and Anomalies",
        path: "/fraud",
        icon: <img src={fraud} alt="" />,
        cName: 'nav-text'
    },
 
  
   
    
  


]

So i need to insert the {t()} into the title of each data tab.

how should i solve this?

Thanks in advance!

2

Answers


  1. Assuming you already have the call for i18n.init somewhere else in your code.

    export const NavbarData = [
        {
            title: 'operationalOverview',
            path: '/monitoringoverview',
            icon: <img  src={startpageIcon} alt="" />,
            cName: 'nav-text'
        },
        {
            title: "performanceQuality",
            path: "/performancequality",
            icon: <img src={performance} alt="" />,
            cName: 'nav-text'
        },
        {
            title: "fraudAndAnomalies",
            path: "/fraud",
            icon: <img src={fraud} alt="" />,
            cName: 'nav-text'
        },
    ]
    

    then on navbar.js

      const { t, i18n } = useTranslation("default", {keyPrefix: "navbar.titles"});
    .
    .
    .
           <nav className={sidebar ? "nav-menu active" : "nav-menu"}>
              <ul className="nav-menu-items" onClick={showSidebar}>
            
                {NavbarData.map((item, index) => {
                  return (
                    <li key={index} className={item.cName}>
                      <Link to={item.path}>
            
                        <span className="navbutton-text" ><span className="navbutton-icon">{item.icon}</span>{t(item.title)}</span> <=== t function inserted here
                        
                        
                      </Link>
                      
                    </li>
                    
                  );
                })}
    
              </ul>
            </nav>
    

    finally on en.json

    {
      "navbar": {
        "titles": {
           "operationalOverview": "Operational Overview",
           "performanceQuality": "Performance Quality",
           "fraudAndAnomalies": "Fraud and Anomalies",
        }
      }
    }
    

    Also, you need an fr.json file with the same structure.

    {
      "navbar": {
        "titles": {
           "operationalOverview": "aperçu opérationnel",
           "performanceQuality": "qualité des performances",
           "fraudAndAnomalies": "fraudes et anomalies",
        }
      }
    }
    
    Login or Signup to reply.
  2. To add internationalization (i18n) to the NavbarData.js file, you can use the useTranslation hook from the react-i18next library. Here’s how you can do it:

    Import the useTranslation hook:

    import { useTranslation } from 'react-i18next';

    Call the useTranslation hook to get the t function:

    const { t } = useTranslation();

    Use the t function to translate the title of each NavbarData item:

    export const NavbarData = [
        {
            title: t('navbar.operationalOverview'),
            path: '/monitoringoverview',
            icon: <img  src={startpageIcon} alt="" />,
            cName: 'nav-text'
        },
        {
            title: t('navbar.performanceQuality'),
            path: '/performancequality',
            icon: <img src={performance} alt="" />,
            cName: 'nav-text'
        },
        {
            title: t('navbar.fraudAndAnomalies'),
            path: '/fraud',
            icon: <img src={fraud} alt="" />,
            cName: 'nav-text'
        },
    ];

    Note that in order to use the t function, you need to have added the translation keys to your i18n resource files, and that you need to wrap the Navbar component with the I18nextProvider component from the react-i18next library in your main App component.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search