Categories
JavaScript React

Using react-intl – Examples

To make an app with internationalization with React, we can use the react-intl library.

Getting Started

We can use it by first installing it by running:

npm install --save react-intl

Then we can create our messages by adding:

index.js:

import React from "react";
import ReactDOM from "react-dom";
import { IntlProvider } from "react-intl";

import App from "./App";

const messages = {
  en: {
    GREETING: "Hello {name}"
  },
  fr: {
    GREETING: "Bonjour {name}"
  }
};

const rootElement = document.getElementById("root");
ReactDOM.render(
  <React.StrictMode>
    <IntlProvider locale="fr" messages={messages["fr"]}>
      <App />
    </IntlProvider>
  </React.StrictMode>,
  rootElement
);

App.js:

import React from "react";
import { FormattedMessage } from "react-intl";

export default function App() {
  return (
    <div className="App">
      <FormattedMessage id="GREETING" values={{ name: "james" }} />
    </div>
  );
}

We have the `messages object for the messages we want to create.

{name} is a placeholder for interpolating text we want to include dynamically.

Then we import the IntlProvider component and wrap it around our app so that we can use react-intl throughout our app.

We also set the locale and the messages object to pass in the messages to our app so we can use it.

Then in App, we use the FormattedMessage component to display our internationalized text.

id is the key of the message in the messages object in index.js.

values has the object that we have in the curly braces.

We have the name property in the object that we pass into the values prop.

This means that {name} is replaced by the value of name in that object.

Dates

We can use the FormattedDate component to format dates. To use it, we write:

import React from "react";
import { FormattedDate } from "react-intl";

export default function App() {
  return (
    <div className="App">
      <FormattedDate
        value={new Date()}
        year="numeric"
        month="long"
        day="numeric"
        weekday="long"
      />
    </div>
  );
}

We keep index.js the same as before, then we’ll see a French date.

The year, month, day, and weekday props can take values to adjust the format.

Internationalized Time

The FormattedTime component is available to format time.

We can write:

import React from "react";
import { FormattedTime } from "react-intl";

export default function App() {
  return (
    <div className="App">
      <FormattedTime value={new Date()} hour="numeric" minute="numeric" />
    </div>
  );
}

to format our dates. We chose to display both the hour and minute as numbers.

Format Numbers.

react-intl can also format numbers. We can use the FormattedNumber component to format numbers.

For instance, we write:

import React from "react";
import { FormattedNumber } from "react-intl";

export default function App() {
  return (
    <div className="App">
      <FormattedNumber value={1000} />
    </div>
  );
}

Plurals

This package can also format plural.

For example, we can write:

import React from "react";
import { FormattedPlural } from "react-intl";

export default function App() {
  return (
    <div className="App">
      <FormattedPlural value={10} one="message" other="messages" />
    </div>
  );
}

one has the singular word, and other has the plural word.

It’s displayed according to the value of value. If value is 1, the singular word is displayed.

Otherwise, plural is displayed.

List

Lists can also be formatted with the FormattedList component.

For instance, we can write:

import React from "react";
import { FormattedList } from "react-intl";

export default function App() {
  return (
    <div className="App">
      <FormattedList type="conjunction" value={["moi", "moi", "toi"]} />{" "}
    </div>
  );
}

We just pass in the array for value. If we keep index.js the same as the first example, then we get French.

So we have ‘moi, moi et toi’ on the screen.

Conclusion

We can use react-intl to internationalize our React apps. It has components to format any string we can think of.

The react-intl examples above will help us do anything with ease.

Categories
JavaScript React

Learning React -Conditional Rendering

Rendering elements or components conditionally is something that we have to do often in React components.

There are a few ways to do this.

If we are rendering something is a condition it true, then we can use the && operator:

{condition && <Component />}

When condition is true then Component will render because the first operand being true will lead to the 2nd expression being evaluated.

If we want to render something when a condition is true and render something else otherwise, then we can use the ternary operator:

{condition ? <Component /> : <OtherComponent />}

If condition is true, then Component will be rendered. Otherwise, OtherComponent will be rendered.

This is handy for conditionals with 2 cases.

If our condition has more than 2 cases, then we have to use if/else or switch statements.

We can use if/else statements as follows:

let comp;
if (foo){
  comp = <Component />;
}
else if (bar){
  comp = <OtherComponent />;
}
else if (baz){
  comp = <AnotherComponent />;
}

We assign comp with the component we want according to the condition that we’ve encountered.

This is the most versatile way to render components based on different cases,

Also, we can use the switch statement by writing:

switch (value){
  case 1: {
    comp = <Component />;
    break;
  }
  case 2: {
    comp = <OtherComponent />;
    break;
  }
  case 3: {
    comp = <AnotherComponent />;
    break;
  }
  default: {
    comp = <DefaultComponent />;
    break;
  }
}

We check the value of value against various values and assign a component to comp based on the value.

Also, we have a default case so that we can render something if the value of value doesn’t match any of the values listed in the case blocks.

We can do conditional rendering with plain JavaScript.

For simple cases, we can use the && or ternary operators.

For more complex cases, we can use if/else or switch statements.

Categories
JavaScript Nodejs React

How to Solve the ‘create-react-app command not found’ Error

The ‘create-react-app command not found’ error occurs because we’re trying to run it locally when it’s not installed.

To fix that, we should run npm i -g create-react-app project-name to install it globally on our computer and run it.

Alternatively, we can also run npx create-react-app project-name to run it without install it.

In both cases, we need Node.js with NPM installed to run create-react-app.

If not, then we’ve to install it.

Categories
Book Reviews JavaScript

Best Books on Web Development

To become a good web developer, we got to read the best books on web development.

They’ll help us a lot, especially if we practice. The following books will help us a lot.

Fundamental Concepts for Web Development: HTML5, CSS3, JavaScript and much more!

This is a good book to introduce us to basic concepts in HTML, CSS, and JavaScript.

It’s very simple and concise. The examples are easy to understand.

This book allows us to understand the most basic building blocks of web development in a flash.

Also, it gives us lots of tips and tricks so that we won’t fall into traps that most beginners fall into.

It also provides us with lots of exercises so that we can master web development quickly.

HTML & CSS, and JavaScript & JQuery

This is another good book on the basics of web development.

It also has chapters on jQuery as a bonus. This is great since jQuery allows us to do more than just JavaScript alone.

Many web apps still use jQuery so we might as well learn it.

This book provides us with all the explanation and examples we need to learn the basics of web development.

It uses a visual approach, which means lots of diagrams, infographics, and photographs to help us learn the ropes.

You Don’t Know JS Series

This is a series of books that we can use to learn the basic and advanced concepts in JavaScript.

If we learn JavaScript thoroughly, we’ll be much better developers as we write better code and work faster.

This book explains the concepts, and also emphasizes how we can avoid the pitfalls of JavaScript.

It has sections about scopes, which is important for writing bug-free code.

Functions are also a topic that this book covers a lot.

Another thing that this book covers are synchronous and asynchronous tasks, which are used everywhere in JavaScript.

Object-oriented programming is also discussed in great detail.

These books are very affordable and will pay for itself many times over if you become proficient developers.

Categories
JavaScript React

React Hooks Equivalent of componentDidMount

When we transition from creating class component to function component, one of things we have to do is find the hook equivalents of the life cycle hooks in class components.

One of the life cycle methods that are used a lot is the componentDidMount method.

It loads when the component is first mounted.

To do the same thing in function components, we use the useEffect hook with an empty array in the 2nd argument.

This lets us commit side effects once when the component first loads.

To use it, we write:

import React, { useEffect, useState } from "react";

export default function App() {
  const [data, setData] = useState({});

  const getData = async () => {
    const res = await fetch("https://api.agify.io/?name=michael");
    const data = await res.json();
    setData(data);
  };

  useEffect(() => {
    getData();
  }, []);

  return <div>{data.name}</div>;
}

We reference the useEffect hook with a callback that calls the getData function.

getData just makes a GET request to an API and get some data. Then it set it as the value of the data state.

The empty array indicates that the callback only loads once when the component first loads.

This is because the array has the values to watch for, and we watch nothing, so it only loads once.

Then we return the data we want to display.

We can have more than one reference to useEffect unlike componentDidMount, so we don’t have to put everything in one callback.

Instead, we can have multiple instances of useEffect with empty arrays as the 2nd argument.

App just loads the data on first load and displays it.