Implement your own styling with i18next

There are two namespaces I am working with:

  • The first namespace is global and contains business-related glossary terms
  • The second namespace is specific to a certain page
// Global Namespace
{
  "amendment": "amendment"
}

// Page Namespace
{
  "action": "Enter your $t(global:amendment) below."
}

In my React component scenario:

import React from 'react'
import { useTranslation } from 'react-i18next';

export function MyComponent() {
  const { t, i18n } = useTranslation();

  return (
    <div>
      <h1>{t('amendment')}</h1>
      <p>{t('action')}</p>
    </div>
  )
}

I would like to change the text inside my h1 element to uppercase.
What would be the most effective way to achieve this?

One solution I thought of is using context, like so:

// Global Namespace
{
  "amendment": "amendment",
  "amendment_uppercase": "Amendment"
}
import React from 'react'
import { useTranslation } from 'react-i18next';

export function MyComponent() {
  const { t, i18n } = useTranslation();

  return (
    <div>
      <h1>{t('amendment', {context: 'uppercase'})}</h1>
      <p>{t('action')}</p>
    </div>
  )
}

The downside here is that it requires duplicating all my translation keys, especially since I have a large global glossary.

Answer №1

To resolve this issue, one approach is to create a custom i18next formatter and assign a specific key for the page, ensuring that the header content starts with an uppercase letter. I have set up a header key which takes the value of "amendment" from the global resources but applies a custom formatter called ucwords.

i18next.init(
  {
    lng: 'en', // Only specify if not using a language detector
    resources: {
      en: {
        global: {
          amendment: 'amendment',
        },
        page: {
          header: '$t(global:amendment, ucwords)',
          action: 'Please enter your $t(global:amendment) below.',
        },
      },
    },
    interpolation: {
      format: function (value, format, lng) {
        if (format === 'ucwords') return [value[0].toUpperCase(), value.slice(1)].join('');
        if (value instanceof Date) return moment(value).format(format);
        return value;
      },
    },
  },
  function (err, t) {
    // Initialization completed
    document.getElementById('header').innerHTML = t('page:header');
    document.getElementById('action').innerHTML = t('page:action');
  }
);
<script src="https://cdn.jsdelivr.net/npm/i18next/dist/umd/i18next.min.js"></script>
<h1 id="header"></h1>
<div id="action"></div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to securely store my JWT Token within my application's state?

userAction.js -> Frontend, Action export const login = (userID, password) => async (dispatch) => { try { dispatch({ type: USER_LOGIN_REQUEST }); const url = "http://localhost:8080/authenticate/"; const ...

What is the best way to pass a variable and its corresponding state-updating function as a prop in a React component?

Considering I have a variable defined as follows: const [APIKey, setAPIKey] = useState([]) Is it possible to group these together into a single variable and then pass it as a prop? const passAPI = {APIKey, setAPIKey} Here is my approach to passing it alo ...

Getting bounding box data from a 3D entity in A-Frame: A simple guide

Currently I'm immersed in a new aframe venture that requires me to import 3D objects of various sizes into my scene. I'm thinking ahead and would like to adjust the object to a specific size (such as a fixed height) before integrating it into the ...

Transferring information from Child to Parent using pure Javascript in VueJS

I am familiar with using $emit to pass data from child components to parent components in VueJS, but I am trying to retrieve that value in a JavaScript function. Here is my situation: Parent Component created () { this.$on('getValue', func ...

When text with delimiters is pasted into a Vuetify combobox, why aren't the chips separated correctly by the delimiters?

I'm attempting to create a Vuetify combobox with chips that automatically split the input based on predefined delimiters, such as ,. This means that if I paste the text a,b,c, the component should convert them into three separate chips: a, b, and c. H ...

Display a JSX string in a React component

I have explored numerous similar questions but haven't found a definitive answer to my query. My dilemma revolves around rendering a JSX template within a string that represents a link, into the binding of a Text component. Here is an excerpt for bet ...

The attempt to generate a .zip file using Node.js with Egg framework was unsuccessful

I developed a Node.js service using Egg framework to send a local .zip file (compressed directory) to the browser, but encountered an issue. Below is the code snippet: Egg.js // Code for zipping files async download() { const ctx = this.ctx; co ...

Display a webpage once its design is completely loaded in Nuxt

I have implemented a layout for my admin pages that displays user information in a consistent format, eliminating the need to fetch this data every time the page reloads. However, I am facing an issue where the page does not wait for the layout to fully l ...

Components undergo a style transformation with Material UI

I've noticed that every time I render the component, the styles keep changing. import React from 'react'; import FormControl from '@material-ui/core/FormControl'; import MenuItem from '@material-ui/core/MenuItem'; im ...

Mongoose TTL still expires despite condition being untrue

Currently, I am facing an issue with my mongoose Schema. I want the model to automatically delete itself after 60 seconds only if the field "paid" is set to false. However, whenever I use TTL (Time To Live), the document expires regardless of the value o ...

What is the best approach for creating a test case for a bootstrap-vue modal component

Exploring ways to effectively test the bootstrap vue modal display function. On the project page, the modal toggles its visibility using the toggleModal method triggered by a button click. The modal's display style is switched between 'none' ...

How can I incorporate custom text when hovering over dates on fullcalendar?

I'm looking to customize the mouseover text inside fullcalendar. Currently, the script only displays the event title on mouseover. You can see a working example here: JS Fiddle Example. How can I modify the code to show my own personalized text on mo ...

What is the best way to track upload progress while using Django?

Is it possible to implement an upload progress bar for a website using Django? I'm interested in tracking the progress of file or image uploads but unsure how to accomplish this. Any tips on retrieving the upload status? ...

Challenges in Implementing Shadows with Animations in ThreeJS MeshDepthMaterial

I'm facing an issue where casting shadows through transparent parts of my Mesh using the MeshDepthMaterial causes the shadows of animated objects to stop moving along with the animation. You can see an example of this problem here: https://jsfiddle.n ...

Enabling Javascript's power-saving mode on web browsers

I created a JavaScript code to play music on various streaming platforms like Tidal, Spotify, Napster, etc., which changes tracks every x seconds. If the last song is playing, it loops back to the first song in the playlist since some websites lack this fe ...

The Collada model in Three.js appeared completely dark until a mouse movement brought in some light

Recently, I've run into a peculiar issue while trying to display a collada model in three.js. It appears that there may be an error in the script logic, but I'm having trouble pinpointing it. The problem is that when the page first loads, the Col ...

What is the best way to add a line break and display HTML content in text using VUE?

I have a string that is passed to the frontend as comeoutside However, in HTML, it needs to be rendered conditionally. const separateFirstFourWords = (words) => { let newStr = `${words.substring(0, 4)} <br> ${words.substring(4, words.length)}`; ...

What is the process for assigning default values to dynamically generated form elements?

I have been working on building a single-page application (SPA) using JavaScript and jQuery. During the process, I encountered an issue with a dynamic form. The user is able to add specific fields as needed, but if they don't generate and utilize all ...

What steps should I follow to properly set up my tsconfig.json in order to ensure that only the essential files are included when executing npm run build

Introduction I am seeking guidance on how to correctly set up my tsconfig.json file to ensure only the necessary files are included when running npm run build for my projects. I want to avoid any unnecessary files being imported. Query What steps should ...