Categories
React Answers

How to add export to CSV button in a React table?

Sometimes, we want to add export to CSV button in a React table.

In this article, we’ll look at how to add export to CSV button in a React table.

How to add export to CSV button in a React table?

To add export to CSV button in a React table, we can use the react-csv library.

To install it, we run:

npm i react-csv

Then we add the button to the table by writing:

import React from "react";
import { useTable } from "react-table";
import { CSVLink } from "react-csv";

const csvData = [
  { firstName: "John", lastName: "Doe" },
  { firstName: "Jane", lastName: "Doe" }
];

const Table = ({ columns, data }) => {
  const {
    getTableProps,
    getTableBodyProps,
    headerGroups,
    rows,
    prepareRow
  } = useTable({
    columns,
    data
  });

  return (
    <table {...getTableProps()}>
      <thead>
        {headerGroups.map((headerGroup) => (
          <tr {...headerGroup.getHeaderGroupProps()}>
            {headerGroup.headers.map((column) => (
              <th {...column.getHeaderProps()}>{column.render("Header")}</th>
            ))}
          </tr>
        ))}
      </thead>
      <tbody {...getTableBodyProps()}>
        {rows.map((row, i) => {
          prepareRow(row);
          return (
            <tr {...row.getRowProps()}>
              {row.cells.map((cell) => {
                return <td {...cell.getCellProps()}>{cell.render("Cell")}</td>;
              })}
            </tr>
          );
        })}
      </tbody>
    </table>
  );
};

export default function App() {
  const columns = React.useMemo(
    () => [
      {
        Header: "Name",
        columns: [
          {
            Header: "First Name",
            accessor: "firstName"
          },
          {
            Header: "Last Name",
            accessor: "lastName"
          }
        ]
      }
    ],
    []
  );

  const data = React.useMemo(() => {
    return csvData.map((d) => Object.values(d));
  }, []);

  return (
    <>
      <CSVLink data={data}>Download me</CSVLink>
      <Table columns={columns} data={csvData} />;
    </>
  );
}

We create the Table component which calls the useTable hook with the columns and data props to return an object that has the properties we use to create the table.

Next, we add a CSV download link by using the CSVLink component.

We pass in a nested array as the value of the data prop so react-csv can generate the CSV from it.

We create the nested array by calling useMemo with a callback that returns the nested array which we create by calling csvData.map with a callback that returns the values in an array from each csvData entry with Object.values.

Now we should see a Download me button which we can click to download the CSV.

Conclusion

To add export to CSV button in a React table, we can use the react-csv library.

Categories
TypeScript Answers

How to get the object length in TypeScript?

Sometimes, we want to get the object length in TypeScript.

In this article, we’ll look at how to get the object length in TypeScript.

How to get the object length in TypeScript?

To get the object length in TypeScript, we can use the Object.keys method and the array length property.

For instance, we write

Object.keys(customer).length;

to return an array of non-inherited keys from the customer object with Object.keys.

Then we get the length of the array with length.

Conclusion

To get the object length in TypeScript, we can use the Object.keys method and the array length property.

Categories
TypeScript Answers

How to add constructor overload with empty constructor in TypeScript?

Sometimes, we want to add constructor overload with empty constructor in TypeScript.

In this article, we’ll look at how to add constructor overload with empty constructor in TypeScript.

How to add constructor overload with empty constructor in TypeScript?

To add constructor overload with empty constructor in TypeScript, we can add different signatures for constructor in our class.

For instance, we write

class Foo {
  constructor();
  constructor(id: number);
  constructor(id: number, name: string, surname: string, email: string);
  constructor(id?: number, name?: string, surname?: string, email?: string) {
    this.id = id;
    this.name = name;
    this.surname = surname;
    this.email = email;
  }
}

to overload constructor by adding different signatures for it.

Then we can do whatever we want with the parameters listed in any signature in the constructor body.

Conclusion

To add constructor overload with empty constructor in TypeScript, we can add different signatures for constructor in our class.

Categories
TypeScript Answers

How to add environment variable with dotenv and TypeScript?

Sometimes, we want to add environment variable with dotenv and TypeScript.

In this article, we’ll look at how to add environment variable with dotenv and TypeScript.

How to add environment variable with dotenv and TypeScript?

To add environment variable with dotenv and TypeScript, we import the dotenv module.

And then we call dotenv.config to load the enviroment variables values from the path specified to load them into process.env.

For instance, we write

import * as dotenv from "dotenv";
dotenv.config({ path: __dirname + "/.env" });

to load the environment variables from __dirname + "/.env" with dotenv.config.

And then the environment variables should be available as properties in process.env.

Conclusion

To add environment variable with dotenv and TypeScript, we import the dotenv module.

And then we call dotenv.config to load the enviroment variables values from the path specified to load them into process.env.

Categories
TypeScript Answers

How to generate UUID in Angular?

Sometimes, we want to generate UUID in Angular.

In this article, we’ll look at how to generate UUID in Angular.

How to generate UUID in Angular?

To generate UUID in Angular, we can use the uuid module.

To install it, we run

npm i uuid

Then we use it by writing

import * as uuid from "uuid";

const myId = uuid.v4();

to import it and then call the v4 function in the uuid module.

Conclusion

To generate UUID in Angular, we can use the uuid module.