Change locale in react-datepicker
Asked Answered
E

7

34

I am using react-datepicker NPM package,
I tried to follow documentation but I was unable to import

registerLocale 

and

setDefaultLocale

from react-datepicker

Do you see where I make mistake?

 import DatePicker from 'react-datepicker';



...
    <DatePicker
            { ...this.props }
            dateFormat={ this.dateFormat }
            ref={ (node) => { this.ref = node; } }
            onClickOutside={ this.clickOutside }
          />
...

this is code where I want to import locale.

Eruptive answered 28/1, 2019 at 9:39 Comment(0)
I
67

First of all make sure you are using the latest version of the plugin (2.0.0). Then you need to also install the date-fns module, but for the moment the react-datepicker is working with the 2.0.0-alpha.23 version.

Then you need to import and register the locale you want and finally add the locale property to the DatePicker

so (after installing the correct versions)

import DatePicker, { registerLocale } from "react-datepicker";
import el from "date-fns/locale/el"; // the locale you want
registerLocale("el", el); // register it with the name you want

and use it

<DatePicker 
    locale="el"
    ...
/>

Working demo at https://codesandbox.io/s/7j8z7kvy06

Impermeable answered 28/1, 2019 at 10:25 Comment(3)
God bless you! I couldn't find this dependency from an alpha-level external library anywhere in the react-datepicker documentation.Caricaria
Any solution for non alpha version of date-fns?Rejoin
Time in extended ui is not localized, need use prop timeCaption: stringNeuter
M
30

For those who don't want to depend on date-fns module you can define your own localization.

Here's a working demo on CodeSandbox.

const days = ['Pt', 'Sa', 'Ça', 'Pe', 'Cu', 'Ct', 'Pz']
const months = ['Ocak', 'Şubat', 'Mart', 'Nisan', 'Mayıs', 'Haziran', 'Temmuz', 'Ağustos', 'Eylül', 'Ekim', 'Kasım', 'Aralık']

const locale = {
  localize: {
    day: n => days[n],
    month: n => months[n]
  },
  formatLong: {
    date: () => 'mm/dd/yyyy'
  }
}

<DatePicker locale={locale} />
Manaker answered 18/2, 2020 at 14:5 Comment(4)
This does not work. TypeError: formatLong.date is not a functionToulouse
I've updated the answer and also put a CodeSandbox link.Manaker
This worked for me although I had to add a match property (empty callback) in locale to make it work properly. I wanted to make appear short month via property useShortMonthInPicker alongside showMonthInPicker but I still see full month. I looked at documentation of Locale type from date-fns but I didn't see how to do thatJerrine
Sounds good - however, for reacent react-datepicker the package itselfe depends on date-fns, so I don't know how useful this is (if it actually reduces the bundle size)Manda
E
6
import React, { Component } from 'react';
import DatePicker, { registerLocale } from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";
import ja from "date-fns/locale/ja";

registerLocale("ja", ja);

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      date: new Date()
    }
    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(date) {
    this.setState({
      date
    });
  }

  render() {
    return (
      <div className="App">
        <body>
          <DatePicker
            dateFormat="yyyy/MM/dd"
            selected={this.state.date}
            onChange={this.handleChange}
            locale='ja'
          />
        </body>
      </div>
    );
  }
}

export default App;

I could get the result you wanted. And I tried to make it with moment library but it didn't work on my code. sorry

Enteritis answered 28/1, 2019 at 12:47 Comment(1)
the npm libraries I used: * date-fns@next * react-datepickerEnteritis
A
6

In case you want to use a locale, that is not supported by date-fns (and those are quite few), you can do a shim.

const monthsBG = ['Януари', 'Февруари', 'Март', 'Април', 'Май', 'Юни', 'Юли', 'Август', 'Септември', 'Октомври', 'Ноември', 'Декември'];
const daysBG = ['нед', 'пон', 'вт', 'ср', 'четв', 'пет', 'съб'];

registerLocale('bg', {
  localize: {
    month: n => monthsBG[n],
    day: n => daysBG[n]
  }, 
  formatLong:{} 
});

and then you can use this locale as any other

<DatePicker
  locale="bg"
  ...
/>
Arabelle answered 9/10, 2019 at 14:55 Comment(1)
Thank u, dude! Greetings from BG.Partan
F
3

You don't even need to use registerLocale, just use import variable name ja without quotes :

<DatePicker
  dateFormat="yyyy/MM/dd"
  selected={this.state.date}
  onChange={this.handleChange}
  locale=ja
/>

You can also set the default locale for all date picker fields with setDefaultLocale :

constructor (props) {
    registerLocale("ja", ja);
    setDefaultLocale("ja");
}

Hope this helps.

Fakery answered 10/7, 2019 at 14:25 Comment(0)
N
2

For dynamic locale imports you could use this code. However, you will get a larger package with dynamic imports:

constructor(props) {
    const getLocale = locale => require(`date-fns/locale/${this.props.language}/index.js`)
    this.locale = getLocale(this.props.language);
}

And then use

<DatePicker locale={this.locale} />
Nekton answered 16/12, 2020 at 15:37 Comment(0)
M
0

Here's how to do it for the latest version 2024+

npm install date-fns

npm install react-datepicker (For .js)

npm i @types/react-datepicker (For .tsx)

Use:

import DatePicker, { registerLocale } from "react-datepicker";

import "react-datepicker/dist/react-datepicker.css";

import vi from "date-fns/locale/vi"; // The locale you want: vi, en, cn, in,..etc .


registerLocale("vi", vi);

View all list code of all country here

          <DatePicker
            locale="vi" //add here
            selected={startDate}
            onChange={(date) => setStartDate(date)}
            selectsStart
            startDate={startDate}
            endDate={endDate}
            className="form-control"
          />

Result:

before:

enter image description here

after:

enter image description here

Millard answered 4/4 at 9:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.