0

I have a React TS app. There I have i18n. Unfortunatelly the base language of the input with date type depends on the browser settings and independent from the langauge selection inside the app.

It is also independent from the lang property.

If English is selected in the browser then it looks like this: enter image description here

But if German is the selected one, than it shows: enter image description here

I have found many question about the topic, but there were no usable responses.

So is it possible to change this text from my React app based on the selected language?

Thanks in advance.

1 Answer 1

0

HTML [ input type="date" ] tag is influenced by the browser and its localization depends on the user's browser settings.

To have full control over the date format and localization, use a custom date picker component.

Install react-datepicker and date-fns

npm install react-datepicker date-fns

then import and fix the code

here is the code

import React, { useState } from 'react';
import DatePicker from 'react-datepicker';
import 'react-datepicker/dist/react-datepicker.css';
import { registerLocale, setDefaultLocale } from 'react-datepicker';
import en from 'date-fns/locale/en-US';
import de from 'date-fns/locale/de';


registerLocale('en', en);
registerLocale('de', de);

const App: React.FC = () => {
  const [startDate, setStartDate] = useState<Date | null>(new Date());
  const [locale, setLocale] = useState<string>('en'); // Default to English

  
  const handleLanguageChange = (event: React.ChangeEvent<HTMLSelectElement>) => {
    setLocale(event.target.value);
  };

  return (
    <div>
      <select onChange={handleLanguageChange}>
        <option value="en">English</option>
        <option value="de">German</option>
      </select>
      <DatePicker
        selected={startDate}
        onChange={(date: Date | null) => setStartDate(date)}
        locale={locale}
      />
    </div>
  );
};

export default App;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.