admin管理员组文章数量:1277309
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
?
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
?
- first thing you're doing wrong is that you're passing the values attribute. Using the declarative api as you're doing, you need to have one id per ponent message. Each label should be unique. What you should do is to change the ids. You have your localized files where they should have the key-value strings, i.e. an en.json file with the content { "app.title": "Hello!"} . Then let's say you have an de.json file with content { "app.title": "Hallo!"} . Then, when you're iterating in your NavLink menu, you must pass the "app.title" in the id attribute. – sergioviniciuss Commented Nov 6, 2018 at 22:31
- your intlProvider that wraps the application will be in charge of loading the localized messages and it will render the ones based on the environment, so when you call the declarative api (<FormattedMessae /> you only need to care about having the right id in it. ) – sergioviniciuss Commented Nov 6, 2018 at 22:33
5 Answers
Reset to default 2I 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:
- 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
ponent around menuItemsIntl[index]
that handles missing keys.
- Flatten out the messages object before injecting it into the provider and then access it via a puted 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 pute 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 recmend the second solution.
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>
);
});
You can use defineMessages
const menuItemsList = menuItems.map((item, index) => {
return (
<li key={index}>
<NavLink to={item.url}>
<FormattedMessage {...MSG[`item_${index}`]} />
</NavLink>
</li>
);
});
const MSG = defineMessages({
item_0: {
id: 'items.service',
defaultMessage: 'Service'
},
item_1: {
id: 'items.contact',
defaultMessage: 'Contact'
}
})
I had a similar problem which I solved by using the select
format. I'd map as usual and use formatMessage()
like so:
const menuItemList = menuItems.map((item, index) => {
return (
<li key={index}>
<NavLink to={item.url}>{intl.formatMessage({
id: "menuItems",
defaultMessage: `{item, select,
home {Home}
contacts {Contacts}
about {About}
}`}, { item: item.name })}
</NavLink>
</li>
);
});
This will be extracted as a single message (with a single ID), which I think is pretty neat. If you have babel-plugin-formatjs
set up, you could even omit IDs, as both the extractor and the plugin generate them automatically.
I used this post to get to my answer although my issue was more generic (just parse an array of strings in my translations file). I am also using typescript. In case anyone here is stuck with the same issue: you can access the messages as kate shows above, but in typescript you also must first cast the object as unknown
first before casting it to a string[]
which can then be mapped normally.
const intl = useIntl();
const safetyTips = intl.messages["safety-tips"] as unknown as string[];
console.log(safetyTips);
<ul>
{safetyTips.map((tip, index) => (
<li key={index}>{tip}</li>
))}
</ul>
本文标签: javascriptHow to render a list of formatted messages using ReactIntlStack Overflow
版权声明:本文标题:javascript - How to render a list of formatted messages using React-Intl - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741246514a2364979.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论