Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to render a list of formatted messages using React-Intl

I have a navigation with standard items like: contact, services, prices, etc... I render it like this:

const menuItemList = menuItems.map((item, index) => {
    return (
        <li key={index}>
            <NavLink to={item.url}>{item.title}</NavLink>
        </li>
    );
});

It works fine. But now I need to translate this navigation and I use react-intl library for this purpose. Accordingly to react-intl doc I have to use FormattedMessage like this:

<p>
   <FormattedMessage id="mainText"/>
</p> 

It works. But how I can use it for list rendering? I think it would work with this, but it doesn't.

const menuItemsList = menuItems.map((item, index) => {
    return (
        <li key={index}>
            <NavLink to={item.url}>
                <FormattedMessage id="mainText" values={item.title}/>
            </NavLink>
        </li>
    );
});

Guys, help please. How to render a list with items in React using FormattedMessage from react-intl?

like image 402
Nastro Avatar asked Oct 10 '18 16:10

Nastro


Video Answer


2 Answers

You need to have messages passed to intl. For example:

{
    profile: 'Profile',
    settings: 'Settings'
}

Also, I suppose that you have

const menuItems = [
    {
        url: '/profile',
        title: 'profile'
    },
    {
        url: '/settings',
        title: 'settings'
    }
] 

So you can use it like this

const menuItemsList = menuItems.map((item, index) => {
    return (
        <li key={index}>
            <NavLink to={item.url}>
                <FormattedMessage id={item.title} />
            </NavLink>
        </li>
    );
});
like image 93
Kate Lizogubova Avatar answered Sep 26 '22 01:09

Kate Lizogubova


I recently had the same problem. React Intl doesn't allow to pass an array to <FormattedMessage />, So assuming you have a large array of translated items like in this english messages object:

{
    "page.title": "Test Page",
    "page.menuItems": ["First english Item", "second english Item", ... , "100th english item"]
}

You'd need a workaround. The idea is that we want to access those items via a nested index instead of a global id.

Now i found two solutions to get this working:

  1. directly access the nested messages in the intl messages via their index (hacky & fast):
import React from "react"
import {useIntl} from 'react-intl'
import NavLink from 'somewhere'

const Menu = ({menuItems}) => {
    const intl = useIntl();
    const menuItemsIntl = intl.messages["page.menuItems"]; 
    return (<div>
        {menuItems.map((item, index) => 
        <li key={index}>
            <NavLink to={item.url}>
                {menuItemsIntl[index]}
            </NavLink>
        </li>}
   </div>);
});

export default Menu;

This has the drawback that you don't have the fallback functionality of React Intl in case you don't have a translation available. You'd need to write your custom FormatMessage component around menuItemsIntl[index] that handles missing keys.

  1. Flatten out the messages object before injecting it into the provider and then access it via a computed unique key (Safe & robust):

We would need the messages object to look like this:

{
    "page.title": "Test Page",
    "page.menuItems.1": "First english Item", 
    "page.menuItems.2": "Second english Item", 
    ...
    "page.menuItems.100": "100th english item"
}

In order to have that we'd need to flatten the original messages object, for example with the following mutating function:

import translations from "./translations.json";

const Root = ()=> {
  const [lan, setLan]= useState("en");
  const messages = translations[lan]
  const flattenMessages = (obj, parKey = "") => {
    Object.keys(obj).forEach((key) => {
      const currKey = parKey + (parKey.length > 0 ? "." : "") + key;
      if (Array.isArray(obj[key]) || typeof obj[key] === 'object') {
        flattenMessages (obj[key], currKey)
      } else if (typeof obj[key] === "string") {
        messages[currKey] = obj[key]
      }
    })
  }
  flattenMessages({...messages})

  return <IntlProvider 
    key={lan}
    messages={messages}
    locale={lan} 
    defaultLocale="en"
    >
       <App />
  </IntlProvider>
};

And later you you just use FormattedMessage with an id like you are used to. You simply need to compute the id string based on the iterator in jsx.

const Menu = ({menuItems}) => {
    return (<div>
        {menuItems.map((item, index) => 
        <li key={index}>
            <NavLink to={item.url}>
                <FormattedMessage id={`page.menuItems.${index}.title`} />
            </NavLink>
        </li>}
   </div>);
});

I wrote the first solution in case somebody didn't know that you can directly access the messages object. For most cases however i would reccommend the second solution.

like image 40
Julian Dm Avatar answered Sep 24 '22 01:09

Julian Dm