Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Where do I put global day.js configuration in a React project so that it applies everywhere?

I want to do the following day.js configuration:

import dayjs from 'dayjs';

// add plugins for timezone functionality
import utc from 'dayjs/plugin/utc';
import timezone from 'dayjs/plugin/timezone';
dayjs.extend(utc);
dayjs.extend(timezone);

// set default timezone
dayjs.tz.setDefault("America/New_York");

// set default format (source: https://stackoverflow.com/a/77459776/22134371)
dayjs.extend((option, dayjsClass, dayjsFactory) => {
    const oldFormat = dayjsClass.prototype.format;
    dayjsClass.prototype.format = function (formatString) {
        return oldFormat.bind(this)(formatString ?? 'YYYY-MM-DD')
    }
});

How do I define this only once in my React project, so that in every file that I use dayjs, it includes these configurations (timezone plugins, default timezone, and overriden format method)?

Thanks for any help!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can just import it on the file that renders your app.

// src/lib/dayjsConfig.js

// all the config stuff you mentioned
// src/index.js

import './lib/dayjsConfig';
import { createRoot } from 'react-dom/client';
import App from './App';

const root = createRoot(document.getElementById('root'));

root.render(<App />);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading