I use momentjs
in my React project. I've implemented the locale configuration via React Context API but it turns out that changing the global locale of momentjs
doesn't affect existing objects. It's a feature since version 2.8.0, see Changing locale globally.
moment.locale(); // 'en'
const m = moment();
m.format("L"); // 11/01/2018
moment.locale("de")); // 'de'
m.format("L"); // 11/01/2018
The LocaleProvider
component switches the locales.
// LocaleProvider class component
onChangeLocale = locale => moment.locale(locale);
A child component renders a locale specific momentjs
instance.
// child element class component
render() {
const { currentDate } = this.state;
return <div>{currentDate.format("L")}<div>;
}
How could I enforce existing momentjs
object to use the changed locale?
I solved the problem by setting the global locale
explicitly with moment.locale()
when rendering the component.
// child element class component
import moment from "moment";
render() {
const { currentDate } = this.state;
return <div>{currentDate.locale(moment.locale()).format("L")}<div>;
}