Categories
JavaScript React

Make Expandable Rows with React-Bootstrap-Table2

With react-bootstrap-table-2, we can create expandable rows with the built in BoostrapTable component.

To use it, we install it by running:

npm install react-bootstrap-table-next --save

Then we write:

import React from "react";
import BootstrapTable from "react-bootstrap-table-next";
import "react-bootstrap-table-next/dist/react-bootstrap-table2.min.css";

const expandRow = {
  renderer: row => <div>age: {row.age}</div>
};

const columns = [
  {
    dataField: "id",
    text: "ID"
  },
  {
    dataField: "firstName",
    text: "first name"
  },
  {
    dataField: "lastName",
    text: "last name"
  }
];

const persons = [
  { id: 1, firstName: "james", lastName: "smith", age: 20 },
  { id: 2, firstName: "alex", lastName: "green", age: 20 },
  { id: 3, firstName: "may", lastName: "jones", age: 18 }
];

export default function App() {
  return (
    <div className="App">
      <BootstrapTable
        keyField="id"
        data={persons}
        columns={columns}
        expandRow={expandRow}
      />
    </div>
  );
}

We import the BootstrapTable component and the css that comes with react-bootstrap-table-2.

Then we create an object called expandRow that displays something in the expanded row.

row has the data for an entry, so we just access the property in the component we return.

columns has the columns data. dataField is for the key for the field of the entry.

text is the column heading text that’s corresponds to the key name.

persons has the data we want to display.

In App, we use the BootstrapTable component by passing in the objects that we created before.

expandRow has the object that’s used to display them items when the row is expanded.

data has the data. keyField has the property name for the unique key.

columns has the data for the columns.

Once we wrote the code above, we see the age field when we click on a row.

With react-bootstrap-table-2, we can make tables with expandable rows without much hassle.

Categories
JavaScript React

React Bootstrap Table Example

We can create tables with React Bootstrap easily.

First, we install React Bootstrap by running:

npm install react-bootstrap bootstrap

Then we can use the built-in Table component as follows:

import React from "react";
import { Table } from "react-bootstrap";
import 'bootstrap/dist/css/bootstrap.min.css';

export default function App() {
  return (
    <div className="App">
      <Table striped bordered hover>
        <thead>
          <tr>
            <th>#</th>
            <th>First Name</th>
            <th>Last Name</th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td>1</td>
            <td>james</td>
            <td>smith</td>
          </tr>
          <tr>
            <td>2</td>
            <td>jacob</td>
            <td>jones</td>
          </tr>
          <tr>
            <td>3</td>
            <td colSpan="2">larry</td>
          </tr>
        </tbody>
      </Table>
    </div>
  );
}

striped bordered hover means that we have a striped table with borders on each cell.

We also need the Bootstrap CSS to style the components.

We can also add variant="dark" as a prop of Table to turn on dark mode.

Also, we can add the responsive prop to Table to make it responsive.

We can make a table easily with React Bootstrap.

Categories
JavaScript React

Formatting Numbers with React

We can format numbers easily with the react-number-format library.

Getting Started

To use it, first we install it by running:

npm install react-number-format --save

Then we can use it by writing the following code:

import React from "react";
import NumberFormat from "react-number-format";

export default function App() {
  return (
    <div className="App">
      <NumberFormat
        value={474849}
        displayType={"text"}
        thousandSeparator={true}
        prefix={"$"}
      />
    </div>
  );
}

We import the NumberFormat component from the react-number-format package.

The value is the number we want to format.

displayType is how we want to display our number. Setting it to 'text' means that we display it as text rather than an input box.

thousandSeparator indicates whether we want to add thousands separator to our formatted number.

prefix is the prefix that we want to put in our number.

Custom Rendering

We can add the renderText prop to with a function that renders a component to render the component our way.

For instance, we can write:

import React from "react";
import NumberFormat from "react-number-format";

export default function App() {
  return (
    <div className="App">
      <NumberFormat
        value={2456981}
        displayType={"text"}
        thousandSeparator={true}
        prefix={"$"}
        renderText={value => <div>{value}</div>}
      />
    </div>
  );
}

We have value => <div>{value}</div> as the value of renderText to render our number in a div.

Grouping Thousands

We can group our thousands in a ways that’s different from the English format.

For example, we can write:

import React from "react";
import NumberFormat from "react-number-format";

export default function App() {
  return (
    <div className="App">
      <NumberFormat
        value={2456981}
        thousandSeparator={true}
        thousandsGroupStyle="lakh"
        prefix={"₹"}
      />
    </div>
  );
}

Then we display the number Indian style.

Changing the Format

We can also change the format of the number.

For example, we can write:

import React from "react";
import NumberFormat from "react-number-format";

export default function App() {
  return (
    <div className="App">
      <NumberFormat value={1111222233334444} format="#### #### #### ####" />
    </div>
  );
}

Then the number is displayed in credit card format.

Input Mask

We can add an input mask by using the mask attribute.

For instance, we can write:

import React from "react";
import NumberFormat from "react-number-format";

export default function App() {
  return (
    <div className="App">
      <NumberFormat
        mask="_"
        value={1111222233334444}
        format="#### #### #### ####"
      />
    </div>
  );
}

Then if we erase it and enter something, underscores will be displayed for digits that haven’t been entered yet.

Conclusion

The NumberFormat component that comes with react-number-format can be great for formatting numbers.

We can display formatted numbers as text or an input box.

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.