Get React-table TS up and running on your local machine using VS Code

Objective:
I am trying to get React-table working with TypeScript on my local computer.

Challenge:
The code is based on this page https://codesandbox.io/s/gkzg3?file=/src/makeData.ts

However, when I attempt to apply the code on my local computer, I encounter some errors.

How can I resolve these errors?

ERROR in src/App.tsx:7:18

TS7031: Binding element 'columns' implicitly has an 'any' type.
     5 | import makeData from './makeData';
     6 |
  >  7 | function Table({ columns, data }) {
       |                  ^^^^^^^
     8 |   const {
     9 |     getTableProps,
    10 |     getTableBodyProps,



ERROR in src/App.tsx:7:27

TS7031: Binding element 'data' implicitly has an 'any' type.
     5 | import makeData from './makeData';
     6 |
  >  7 | function Table({ columns, data }) {
       |                           ^^^^
     8 |   const {
     9 |     getTableProps,
    10 |     getTableBodyProps,


ERROR in src/makeData.ts:26:34

TS7019: Rest parameter 'lens' implicitly has an 'any[]' type.
    24 | }
    25 |
  > 26 | export default function makeData(...lens) {
       |                                  ^^^^^^^
    27 |   const makeDataLevel = (depth: number = 0) => {
    28 |     const len = lens[depth];
    29 |     return range(len).map(d => {


TS7023: 'makeDataLevel' implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions.
    25 |
    26 | export default function makeData(...lens) {
  > 27 |   const makeDataLevel = (depth: number = 0) => {
       |         ^^^^^^^^^^^^^
    28 |     const len = lens[depth];
    29 |     return range(len).map(d => {
    30 |       return {

https://i.sstatic.net/DBVrb.png

https://i.sstatic.net/gVqMH.png

Additional Information:
*I am new to react-table.
*The code I am using is identical to the one on this page (https://codesandbox.io/s/gkzg3?file=/src/makeData.ts). It runs successfully on sandbox but encounters issues on my local computer while using VS Code. *TypeScript is being utilized.

Thank you


App.tsk

import React from 'react';
import logo from './logo.svg';
import './App.css';
import { useTable } from 'react-table';
import makeData from './makeData';

function Table({ columns, data }) {
  const {
    getTableProps,
    getTableBodyProps,
    headerGroups,
    rows,
    prepareRow
  } = useTable({
    columns, data
  })
  // Render the UI for your table
  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',
          },
        ],
      },
      {
        Header: 'Info',
        columns: [
          {
            Header: 'Age',
            accessor: 'age',
          },
          {
            Header: 'Visits',
            accessor: 'visits',
          },
          {
            Header: 'Status',
            accessor: 'status',
          },
          {
            Header: 'Profile Progress',
            accessor: 'progress',
          },
        ],
      },
    ],
    []
  )

  const data = React.useMemo(() => makeData(20), []);
  return (
    <Table columns={columns} data={data} />
  );
}

makeData.ts

import namor from 'namor';

const range = (len: number) => {
  const arr = [];
  for (let i = 0; i < len; i++){
    arr.push(i);
  }
  return arr;
}

const newPerson = () => {
  const statusChange = Math.random();
  return {
    firstName: namor.generate({ words: 1, numbers: 0}), 
    lastName: namor.generate({ words: 1, numbers: 0}),
    age: Math.floor(Math.random() * 30),
    visits: Math.floor(Math.random() * 100),
    progress: Math.floor(Math.random() * 100),
    status:
      statusChange > 0.66 ?
        'relationship' : statusChange > 0.33 ?
        'complicated' : 'single'
  }
}

export default function makeData(...lens) {
  const makeDataLevel = (depth: number = 0) => {
    const len = lens[depth];
    return range(len).map(d => {
      return {
        ...newPerson(),
        subRows: lens[depth + 1] ? makeDataLevel(depth + 1) : undefined,
      }
    })
  }

  return makeDataLevel();
}

Answer №1

Fortunately, I had success working with React TS on my local computer.

*To make it work, you must install these two packages via npm: "@types/react-table" and "react-table"
*https://stackblitz.com/edit/react-ts-vk79wd


app.tsx

import React, { useState, useEffect } from 'react';
import { useTable, Column, useSortBy } from 'react-table';
import axios from 'axios';

const columns: Column<Data>[] = [
  {
    Header: 'login',
    accessor: 'login',
  },
  {
    Header: 'id',
    accessor: 'id',
  },
  {
    Header: 'node id',
    accessor: 'node_id',
  },
  {
    Header: 'type',
    accessor: 'type',
  },
];

interface Data {
  login: number;
  id: string;
  node_id: string;
  type: string;
}

export default function App() {
  const [data, setData] = useState([]);
  React.useMemo(
    () =>
      handleData().then((res) => {
        setTimeout(() => {
          setData(res);
        }, 1000);
      }),
    []
  );

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

  async function handleData() {
    const fetchData = async () => {
      const response = await axios.get('https://api.github.com/users');
      return await response.data;
    };

    return Promise.resolve(fetchData());
  }

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

  return (
    <table {...getTableProps()}>
      <thead>
        {headerGroups.map((headerGroup) => (
          <tr {...headerGroup.getHeaderGroupProps()}>
            {headerGroup.headers.map((column) => (
              <th {...column.getHeaderProps(column.getSortByToggleProps())}>
                {console.log(column.getSortByToggleProps())}
                {column.render('Header')}
                <span>
                  {' '}
                  {column.isSorted
                    ? column.isSortedDesc
                      ? ' 🔽'
                      : ' 🔼'
                    : ''}{' '}
                </span>
              </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>
          );
        })}
        {rows.length === 0 && (
          <tr>
            <td colSpan={2}>loading...</td>
          </tr>
        )}
      </tbody>
    </table>
  );
}

react-table.d.tsx

import {
  UseSortByColumnOptions,
  UseSortByColumnProps,
  UseSortByInstanceProps,
  UseSortByOptions,
  UseSortByState,
} from 'react-table';

declare module 'react-table' {
  export interface TableOptions<D extends object> extends UseSortByOptions<D> {}

  export interface TableInstance<D extends object = {}>
    extends UseSortByInstanceProps<D> {}

  export interface TableState<D extends object = {}>
    extends UseSortByState<D> {}

  export interface Column<D extends object = {}>
    extends UseSortByColumnOptions<D> {}

  export interface ColumnInstance<D extends object = {}>
    extends UseSortByColumnProps<D> {}
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

selectize.js typescript: Unable to access values of an undefined object (reading '0')

I've been working on incorporating selectize.js into my project using webpack and typescript. After installing selectize.js and the necessary types, I added the following to my code: yarn add @selectize/selectize yarn add @types/select2 Within my c ...

Alter the attributes of an instance in a class using a function

Attempting to explain a simple method in TypeScript. This method should allow modification of data for any object type within the data attribute. In simpler terms, we can modify, add, or remove data based on the specified data type, and TypeScript facilit ...

Experiencing an Issue with NGINX Loading Vue 3 Vite SPA as a Blank White Page

I currently have the following NGINX configuration set up: events { worker_connections 1024; } http { server { listen 80; server_name localhost; location / { root C:/test; index index.html; ...

issues arise post-transpilation with creating errors

In order to practice, I decided to create a basic TypeScript project. If it could be helpful, here is my ts.config: { "compilerOptions": { "target": "es2016", "module": "commonjs", "outDir": "./dist", "esModuleInterop": true, "forceC ...

Utilizing Typescript to extract type information from both keys and values of an object

I have a unique challenge of mapping two sets of string values from one constant object to another. The goal is to generate two distinct types: one for keys and one for values. const KeyToVal = { MyKey1: 'myValue1', MyKey2: 'myValue ...

Transforming the unmanaged value state of Select into a controlled one by altering the component

I am currently working on creating an edit form to update data from a database based on its ID. Here is the code snippet I have been using: import React, {FormEvent, useEffect, useState} from "react"; import TextField from "@material ...

When working with the latest version of Angular CLI, make sure to include a @NgModule annotation in

Just a heads up: I'm diving into Angular for the first time, so bear with me if I make some rookie mistakes. The Lowdown I've got the latest version of Angular CLI up and running The default app loads without a hitch after 'ng serve' ...

Building a dropdown menu component in react native

Looking to implement a dropdown menu in React Native using TypeScript. Any suggestions on how to achieve this for both iOS and Android platforms? Check out this example of a dropdown menu ...

Encountered Typescript issue when utilizing typed forms in Angular

Below is the interface I am working with: export interface ILoginDto { email: string; password: string; } Here is a snippet of the relevant code from the component: import { FormBuilder, FormGroup, Validators } from '@angular/forms'; export ...

Filter through the array using the cast method

Trying to implement this: let selections = list.filter(obj => obj.type === "myType"); An issue arises with the filter function displaying an error message which states 'filter' does not exist on type 'NodeType' I attempted to ...

The Angular 6 test command using npm has encountered a failure

I've been encountering a disconnect error while attempting to run Angular test cases. With over 1500 test cases written, it appears that the sheer volume may be causing this issue. Is there a way to resolve the disconnect error when running such a lar ...

Angularfire2 retrieve list of data with a specified number of items from the

I am facing a challenge in retrieving a specific node from my firebase database. The technologies I am using include: "angularfire2": "^5.0.0-rc.4", "firebase": "^4.9.0", In my component code, you can find the following lines : this.id = this.route. ...

How can I retrieve the express Application within a REST API?

After reviewing Massive's documentation and learning that saving the connection object to Express's application settings can help reduce database connection execution time, I encountered a problem. How can one access the Express app variable when ...

Is it possible to regulate the type of a class that has not yet been instantiated?

Is there a method in typescript to restrict the type of an uninstantiated class? I am looking to specify that only classes which inherit from Repository can be accepted by the addRepository method without actually creating an instance of the class (its co ...

Removing a value from a hashmap using Typescript - what is the best way to do it?

After successfully implementing a hashmap in typescript following a helpful post, I am facing an issue with removing something from the hashmap. TypeScript hashmap/dictionary interface To add a key to the keys field of my abstract Input class's hash ...

Sometimes the downloaded xlsx file may become corrupted

Currently, I am working on developing a project using Angular4 with Typescript. One of the tasks involved creating a blob utilizing the XLSX-populate library. Below is an example showing the code snippet for generating a valid xlsx object: var url = wind ...

When TypeScript error "ts(18004)" occurs, it is because of the object properties within all Prisma DB

I am currently in the process of verifying if a user's email already exists. To achieve this, I am utilizing Prisma Client's findUnique method. Below is the code snippet I have implemented: const userWithEmail = await prisma.user.findUnique({ ...

I am having trouble getting Angular 6 to work with lowdb

I am currently in the process of developing an Electron app with Angular 6, utilizing lowdb as a local database. This is all very new to me and I am learning through trial and error. However, I seem to be encountering difficulty resolving the following er ...

Implement a class attribute to the parent <div> element using React and TypeScript

I'm trying to figure out how to achieve this task. I need to assign a class upon clicking on an element that is not directly in my code, but rather in one of its parent elements. My initial thought was to accomplish this with jQuery using the followi ...

What is the best way to access the input element of ng-content from the parent component?

Creating a unique component in the following structure <div class="custom-search-field" [ngClass]="{'expanding': expanding}"> <ng-content></ng-content> </div> When using this component, users are expected to include ...