'Multiple locales with date-fns in ReactJs
Using date-fns, i am trying to add multiple locales in my app, before i hade one only locale so the import was simply like this :
import {fr as locale} from 'date-fns/locale';
import {format} from 'date-fns'
And i was using the locale as follow in the component :
<DateSingleInput
dayLabelFormat={(date) => format(date, 'dd', {locale})}
/>
But now i have 3 locales, fr, en and es, i get these locales from the html file as props. i have updated the import like this :
import {fr, en, nl} from 'date-fns/locale';
And in the component i made this change so i can get the current locale, the fr is the default language :
<DateSingleInput
dayLabelFormat={(date) => format(date, 'dd', this.props.locale ? this.props.locale : 'fr')}
/>
What am i doing wrong?
After many attemps i have noticed that i need to mention the current locale in the format function, for example when i add fr or nl or fr it works, here is the code :
<DateSingleInput
dayLabelFormat={(date) => format(date, 'dd', { locale : fr })}
/>
But when i put the props or a function to put the perfet locale i get an error RangeError: locale must contain localize property
<DateSingleInput
dayLabelFormat={(date) => format(date, 'dd', { locale : this.props.locale ? this.props.locale : 'fr' })}
/>
Solution 1:[1]
I think your default local string 'fr' is not accepted by the format function as the parameter is not what the function waits for. If you print any locale that you have imported you will see that those locales are objects and not just a string. If you remove the simple quotes in the 'fr' fallback parameter and use the imported fr locale as an object this will work!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | reset4 |