Some Libraries That I Use For Every React Projects

-

When I ask you about “What is ReactJS?”, the first thing that comes to mind is “components“. And the second is “reusability“. Whenever you start a new project with React, you always do some clean-up work for your project. Deleting test files, deleting comments, deleting CSS codes, and even deleting the content of “App.js” files. That is not the only case for me. I am doing this clean-up work as well. However, I am also installing some libraries immediately. I don’t even ask myself that “Am I gonna need this library in this project?”. There are some libraries that are extremely useful and necessary to develop a new React project. In my opinion, those libraries are “must”. 🙂

1. lodash (_)

Lodash is a powerful utility library that comes with extremely useful functions that you are going to use in your projects for sure. It also comes with modularity and performance. It has some functions of JavaScript that are redefined and improved. It also has some other functions that you might need someday. First, let’s see how we install this library.

npm i --save lodash

Then you can simply import:

import _ from 'lodash';

Yes, you import “_” (underscore) to use this library. Underscore was their old name. On the other hand, since you are using some functions that are already defined in JavaScript, it is a good practice to name “lodash” as “_”. You will understand what I mean soon.

Let’s write some examples.

const pokemons = ['charmander', 'pikachu', 'bulbasaur', 'snorlax'];
const lengthOfPokemons = _.map(pokemons, pokemon => pokemon.length); // [10, 7, 9, 7]

The above example returns the number of characters on each Pokemon name.

You can also define a function, and give it as a second parameter of a “map” function.

function square(x) {
  return x * x;
}

const numbers = [3, 6, 4, 5, 1];
const squared = _.map(numbers, square);
console.log(squared); // [9, 36, 16, 25, 1]

Pretty easy, huh?

There are many more functions in lodash. You can check the documentation and see what you are capable of with this library.

One important thing worth mentioning is that the advantage of lodash, it handles errors for you. If you try to map a null value, you will get an error. However, that is not the case for lodash.

2. moment

While you are developing an application such as a blog or weather, you will notice that you need some kind of parser to parse dates. Sometimes, it is not easy to deal with dates because of time differences with different geo zones. At this point, “moment” utilizes everything for us and we don’t have to worry about those annoying processes.

Parsing, validating, manipulating, and displaying dates are very easy with moment.

npm install moment --save   # npm
yarn add moment             # Yarn
Install-Package Moment.js   # NuGet
spm install moment --save   # spm
meteor add momentjs:moment  # meteor

Then you can import:

import moment from 'moment';

Let’s see some examples.

Formatting Dates

moment().format('MMMM Do YYYY, h:mm:ss a'); // September 12th 2020, 1:34:51 pm
moment().format('dddd');                    // Saturday
moment().format("MMM Do YY");               // Sep 12th 20
moment().format('YYYY [escaped] YYYY');     // 2020 escaped 2020
moment().format();

Relative Times

moment("20111031", "YYYYMMDD").fromNow(); // 9 years ago
moment("20120620", "YYYYMMDD").fromNow(); // 8 years ago
moment().startOf('day').fromNow();        // 14 hours ago
moment().endOf('day').fromNow();          // in 10 hours
moment().startOf('hour').fromNow();       // 36 minutes ago

Calendar Time

moment().subtract(10, 'days').calendar(); // 09/02/2020
moment().subtract(6, 'days').calendar();  // Last Sunday at 1:36 PM
moment().subtract(3, 'days').calendar();  // Last Wednesday at 1:36 PM
moment().subtract(1, 'days').calendar();  // Yesterday at 1:36 PM
moment().calendar();                      // Today at 1:36 PM
moment().add(1, 'days').calendar();       // Tomorrow at 1:36 PM
moment().add(3, 'days').calendar();       // Tuesday at 1:36 PM
moment().add(10, 'days').calendar();      // 09/22/2020

Multiple Locale Support

moment.locale();         // en
moment().format('LT');   // 1:36 PM
moment().format('LTS');  // 1:36:33 PM
moment().format('L');    // 09/12/2020
moment().format('l');    // 9/12/2020
moment().format('LL');   // September 12, 2020
moment().format('ll');   // Sep 12, 2020
moment().format('LLL');  // September 12, 2020 1:36 PM
moment().format('lll');  // Sep 12, 2020 1:36 PM
moment().format('LLLL'); // Saturday, September 12, 2020 1:36 PM
moment().format('llll'); // Sat, Sep 12, 2020 1:36 PM

There is detailed and well-prepared documentation as well. You can check it out to learn more about moment.

3. i18next & react-i18next

In the company that I am working on, we are developing an international application. Therefore supporting multiple languages such as Arabic, Turkish, English is a crucial part to satisfy our customers. Supporting multiple languages is now very easy with the help of i18next. You just have to map translation strings with common keys and i18next will handle the rest for you.

On the other hand, you also have to detect user’s browser language to give them the best user experience. Sometimes you will have to let your users choose which language they want to use. All these capabilities are handled pretty well with i18next.

npm install i18next react-i18next --save

There are different usage of i18next in your React components. I will give some example cases so that you can have an opinion. However, to be able to use the library as best as you can, you have to check the documentation out.

Before:

import React from 'react';
import { withTranslation } from 'react-i18next';

const Test = ({ t }) => {
  return (
    <div>
      Hello world!
    </div>
  )
}

export default withTranslation()(Test);

After:

import React from 'react';
import { withTranslation } from 'react-i18next';

const Test = ({ t }) => {
  return (
    <div>
      {t('helloWorld')}
    </div>
  )
}

export default withTranslation()(Test);

This is one way of using i18next. There are other ways such as using hooks and so on.

What I want to mention is that before using i18next like this, you need to do some configuration and you need to tell i18next where you put translation strings.

First of all, in the root directory of your project where your “App.js” file located, create a new file named “i18n.js”.

import i18n from "i18next";
import { initReactI18next } from "react-i18next";

import translationEN from './translation/en.json';
import translationTR from './translation/tr.json';

const resources = {
  tr: {
    translation: translationTR
  },
  en: {
    translation: translationEN
  }
};

i18n
  .use(initReactI18next) // passes i18n down to react-i18next
  .init({
    resources,
    lng: "en",
    fallbackLng: "en",

    interpolation: {
      escapeValue: false
    }
  });

export default i18n;

The above example simply says:

  • I have two different languages: Turkish and English.
  • My language files are located in “./translation/en.json” and “./translation/tr.json”
  • Variable “resources” is an object that takes key-value pairs where the key is the abbreviation of the language and value is another object. This object has “translation” property which takes the translation file which is a “json” file.
  • “lng” means the default language and “fallbackLng” is the language if the given language was not found.
  • Normally, React handles “escapeValue” thing for the security but we still put this in a configuration file so that we make sure everything works fine.

Lastly, we create our translation “json” files to hold our translation strings. For example:

en.json

{
  "helloWorld": "Hello world!"
}

tr.json

{
  "helloWorld": "Merhaba dünya!"
}

That’s all you have to do. Now, you can use your project with multiple language support. As I mentioned before, remember to read documentation to get more information.

4. WebFontLoader

Using the correct font while designing your application is one of the most important and difficult things to do. While adding multiple fonts to your project, you also have to be careful to make sure your application doesn’t slow down. There are a couple of ways to handle this of course. There are best practices and other things. In my opinion, the easiest way is to use “Web Font Loader“. With the help of Web Font Loader, you can easily import any kind of fonts including Google’s fonts or custom fonts.

npm i webfontloader

Edit your App.js file and add the following code:

import WebFont from 'webfontloader';

WebFont.load({
  google: {
    families: ['Cormorant Infant', 'Nunito:400, 600']
  }
});

function App() {
  return ...
}

export default App;

Right now, you can use “Cormorant Infant” and “Nunito” font families in your project. There are many other configurations and customizations. You can check this documentation out.

FEATURED PİCTURE CREATED BY FREEPİK – WWW.FREEPİK.COM

Share this article

Recent posts

Some Libraries That I Use For Every React Projects

When I ask you about "What is ReactJS?", the first thing that comes to mind is "components". And the second is "reusability". Whenever you start a new project with React, you always do some clean-up work for your project. Deleting test files, deleting comments, deleting CSS codes, and even deleting the content of "App.js" files. That is not the only case for me. I am doing this clean-up work as well. However, I am also installing some libraries immediately. I don't even ask myself that "Am I gonna need this library in this project?". There are some libraries that are extremely useful and necessary to develop a new React project. In my opinion, those libraries are "must".

Geliştirme Hızınızı Arttıracak Bir VS Code Özelliği: Snippets

React, HTML vb. alanlarda kod yazarken, eğer programlama yeni başlamadıysanız ve Youtube'da siz de herkes gibi videolar izleyip öğrenmeye çalışıyorsanız, herkesin kullandığı bir özelliği...

JavaScript Best Practices ve Coding Conventions – Clean Code

Even bad code can function. But if code isn’t clean, it can bring a development organization to its knees. Robert C. Martin

Popular categories

CEVAP VER

Please enter your comment!
Please enter your name here