Replies: 1 comment
-
Just build a lookup object or map so you can access them dynamically. Here's a little React demo: import { frCA, enUS, ptBR } from "date-fns/locale";
import { formatDistance } from "date-fns";
import { useState } from "react";
const localesMap = {
"en-US": ["English (USA)", enUS],
"fr-CA": ["French (Canada)", frCA],
"pt-BR": ["Portuguese (Brazil)", ptBR]
};
export default () => {
const [selectedLocaleCode, setSelectedLocaleCode] = useState("en-US");
const bday = new Date(2010, 0, 1);
const locale = localesMap[selectedLocaleCode][1];
const msg = formatDistance(bday, new Date(), { locale });
return (
<>
<select
value={selectedLocaleCode}
onChange={(e) => setSelectedLocaleCode(e.currentTarget.value)}
>
{Object.keys(localesMap).map((localeCode) => {
const localeName = localesMap[localeCode][0];
return <option value={localeCode}>{localeName}</option>;
})}
</select>
{msg}
</>
);
}; |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Hi there, I am using Next.js and date-fns. On my profile page, I have an item that displays the date the user registered, but using formatDistance().
This outputs perfectly in Spanish using the locale import, but I want to put a dynamic value on locale: to switch different languages based on the locale or the URL, so I use the locale variable from Next.js and I get this error:
I plan to use 4 o 5 locales on my website, and it would be nice to have this dynamic.
Beta Was this translation helpful? Give feedback.
All reactions