Sometimes, we want to access nested messages with react-intl.
In this article, we’ll look at how to access nested messages with react-intl.
Access Nested Messages with react-intl
To access nested messages with react-intl, we can flatten the messages object into an object without nested propeties.
We can use the flatten
function from the flat
NPM package to do this.
For instance, we write:
import React from "react";
import flatten from "flat";
import { IntlProvider, FormattedMessage } from "react-intl";
const messages = {
message: "some message",
nested: {
anotherMessage: "another message"
}
};
export default function App() {
return (
<IntlProvider messages={flatten(messages)} locale="en" defaultLocale="en">
<p>
<FormattedMessage id="nested.anotherMessage" />
</p>
</IntlProvider>
);
}
We have the messages
object with a nested message.
Then to access nested.anotherMessage
, we call the flatten
function with messages
and then we set that as the value of the messages
prop of IntlProvider
.
And then we set the id
prop of FormattedMessage
to nested.anotherMessage
to show the message.
Therefore, we should see another message
on the screen.
Conclusion
To access nested messages with react-intl, we can flatten the messages object into an object without nested propeties.
We can use the flatten
function from the flat
NPM package to do this.