DEV Community

loading...

How to localize Material UI DatePicker to your preferred locale in React

raphaelchaula profile image Raphael Chaula ・2 min read

Material UI DatePickers are usually in English language i.e en locale but sometimes you wish they were in your first language for instance mine is Swahili, sw locale.

Here is how, after you have created a React app and added Material UI to it you need more libraries: @material-ui/pickers, @date-io/core, @date-io/date-fns, @date-io/moment, date-fns and moment.

When installing them there might be some compatibility issues so make sure you use compatible libs for the @material-ui/pickers you are using, for my case, I use @material-ui/pickers version 3 so here are its compatibe libs versions.

yarn add @material-ui/pickers@^3.0.0

yarn add @date-io/date-fns@^2.0.0
yarn add @date-io/moment@^1.0.0
yarn add @date-io/core@^1.0.
yarn add date-fns@^2.0.0
yarn add moment@^2.0.0
Enter fullscreen mode Exit fullscreen mode

DatePickerComponent.js

import React from 'react';
import { DatePicker, MuiPickersUtilsProvider } from "@material-ui/pickers";
import { createMuiTheme, ThemeProvider} from '@material-ui/core/styles';
import MomentUtils from "@date-io/moment";
import moment from "moment";
import "moment/locale/sw";

const DatePickerComponent = ({ date, setDate}) => {

  const theme = createMuiTheme({
    palette: {
      primary: {
        main: '#2EC4B6'
      },
      secondary: {
        main: '#2EC4B6'
      },
    },
  });

  return (
    <ThemeProvider theme={theme}>
      <MuiPickersUtilsProvider libInstance={moment} utils={MomentUtils} locale={"sw"} >
        <DatePicker
          required
          format="L"
          clearable
          okLabel="Sawa"
          clearLabel="Futa"
          cancelLabel="Hairisha"
          value={date}
          variant="dialog"
          maxDateMessage=""
          mask="__/__/____"
          placeholder="dd/MM/yyyy"
          onChange={(dateChanged) => setDate(dateChanged)}
          views={["year", "month", "date"]}
          InputProps={{ disableUnderline: true }}
        />
      </MuiPickersUtilsProvider>
    </ThemeProvider>
  );

};

export default DatePickerComponent;
Enter fullscreen mode Exit fullscreen mode

Replace sw in the DatePickerComponent with the locale you prefer you will have it in your locale, here is how mine looks.

Alt Text Alt Text

Happy Hacking!

Discussion (0)

pic
Editor guide