Tips for utilizing the index and style attributes when passing them to the Row function in React-Window

Currently, I am attempting to define the index and style parameters passed to the Row function in TypeScript.

//https://github.com/bvaughn/react-window

import * as React from "react";
import styled from "styled-components";
import { FixedSizeList as List } from "react-window";
import AutoSizer from "react-virtualized-auto-sizer";

const StyledSection = styled.section`
  width: 100vw;
  height: 100vh;
  background: #C0C0C0;
`;

const Row = ({ index, style }: {index: number, style: any}) => (
  <div className={index % 2 ? 'ListItemOdd' : 'ListItemEven'} style={style}>
    Row {index}
  </div>
);

const Scroller = () => {
  return (
    <StyledSection>
      <AutoSizer>
        {({ height, width }) => {
          return (
            <List height={height} width={width} itemSize={20} itemCount={300}>
              {Row}
            </List>
          );
        }}
      </AutoSizer>
    </StyledSection>
  );
};

export { Scroller };

In the above snippet, I have attempted to explicitly type the index parameter as a number while keeping the style parameter as any. However, an error stating "index is not defined" is displayed by the compiler.

   const Row = ({ index, style }) => (
      <div className={index % 2 ? 'ListItemOdd' : 'ListItemEven'} style={style}>
        Row {index}
      </div>
    );

Do you have any suggestions on how to properly assign types to these two parameters? The react-window library includes its own d.ts file. You can view a functional example on CodeSandbox - https://codesandbox.io/s/infinite-scroller-52b7d?file=/src/Scroller.tsx

Answer №1

Are you looking for this information?

import { CSSProperties } from 'react';

const Row = ({ index, style }: { index: number; style: CSSProperties; }) => (
  <div className={index % 2 ? 'ListItemOdd' : 'ListItemEven'} style={style}>
    Row {index}
  </div>
);

Enhance your code by adding types with object destructuring. Utilize your IDE to easily find the type of style, simply by using goto declaration on the first instance of style within style={style}. (Try ctrl-b or ctrl-q in jetbrain IDE, for VScode refer to the respective shortcuts).

Answer №2

Enhance the List child component by utilizing the available types from the @types/react-window package. The types can be accessed here.

To implement this in your scenario, follow these steps:

  1. Begin by installing @types/react-window as a dev dependency.
  2. Next, import the ListChildComponentProps type from the installed package.
import React from 'react'
import { ListChildComponentProps } from 'react-window'

const Row: React.FC<ListChildComponentProps> = ({ index, style }) => (
  <div className={index % 2 ? 'ListItemOdd' : 'ListItemEven'} style={style}>
    Row {index}
  </div>
);

For Advanced users

If you need the data prop to have proper typing, you can assign a custom type/interface to the ListChildComponentProps.

import React from 'react'
import { ListChildComponentProps } from 'react-window'

interface Person {
  name: string
  email: string
}

const Row: React.FC<ListChildComponentProps<Person[]>> = ({ index, style, data }) => (
  <div style={style}>
    {data[index].name} - {data[index].email}
  </div>
);

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

Next.js is failing to infer types from getServerSideProps to NextPage

It seems like the data type specified in getServerSideProps is not being correctly passed to the page. Here is the defined model: export type TypeUser = { _id?: Types.ObjectId; name: string; email: string; image: string; emailVerified: null; p ...

Steer clear of using sourceMap files

Here is the content of my tsconfig.json file: { "compilerOptions": { "target": "es5", "module": "commonjs", "moduleResolution": "node", "sourceMap": true, "emitDecoratorMetadata": true, "experimentalDecorators": true, "remove ...

Setting the initial navigation theme based on route parameters from an external source, not within the StackNavigator

Is there a way to set the initial navigation theme based on the current route params without rendering the NavigationContainer and causing a flash of content with the default theme? Can the route be accessed from outside of the NavigationContainer without ...

What is the process for configuring React on one server and springboot on a separate server?

Can you help me with the setup of the following: Web Server : I need to set up a react + typescript application using npm at Backend Server : I also need to configure a Springboot backend server at I am currently using webpack to build the react applica ...

Error: The code is unable to access the '0' property of an undefined variable, but it is functioning properly

I am working with two arrays in my code: bookingHistory: Booking[] = []; currentBookings: any[] = []; Both arrays are populated later in the code. The bookingHistory array consists of instances of Booking, while currentBookings contains arrays of Booking ...

The object's key values were unexpectedly empty despite containing data

There's an issue with my object - it initially gets key values, but then suddenly loses them all. All the key values become empty and a message appears in the console for the object: "this value was evaluated upon first expanding. it may have ch ...

Tips for converting each item within an array into its own separate element

https://i.sstatic.net/Dxj1W.pngI currently have an array of objects that I am utilizing to generate a table in Angular. The table is functioning properly and successfully displays the data. However, I now have a requirement to enable editing for each indiv ...

Checkboxes within Angular's reactive forms are a powerful tool for creating dynamic user

Currently, I am working on a contact form that includes checkboxes for users to select multiple options, with the requirement of selecting at least one box. My challenge lies in figuring out how to pass all the selected checkboxes' data to an API usin ...

Basic library using babel, TypeScript, and webpack - Error: (...) is not a recognized function; within Object.<anonymous>

Recently, I encountered a strange issue while trying to bundle a simple function using babel, typescript, and webpack. You can find the example that is not working at this link. To test it, simply download the code, run npm/yarn install, npm/yarn run buil ...

Struggling to understand how to properly 'map' my data from the response in Next.js 13 using Typescript

Just a few days into my journey with next.js, and I'm already facing a challenge in figuring out how to fetch data from an API. In regular React, I would typically use useState and useEffect for managing state and fetching data. But when it comes to n ...

Develop a Nativescript Angular component dynamically

Is there a way for me to dynamically generate a Component and retrieve a View object to insert into a StackLayout? ...

Encountering errors in Visual Studio when trying to work with node_modules directories that have a tsconfig

In my current project, there is a tsconfig.json file located in the root directory. Strangely, Visual Studio keeps throwing errors related to other instances of tsconfig.json found in different packages, as shown below: https://i.sstatic.net/T7Co2.png Ev ...

Error Encountered (TypeError): Unable to access attributes of undefined (attempting to read 'appendChild')

I have been working on creating a choropleth Map of AntV using React.js with functional components. This is the code snippet for my chart: import DataSet from '@antv/data-set'; import { Chart } from '@antv/g2'; const CustomerByRegion = ...

Change an array of objects into a map where each object is indexed by a unique key

I'm attempting to transform an array of objects into a map, with the index based on a specific attribute value of the object in typescript 4.1.5 Additionally, I am only interested in attributes of a certain type (in this case, string) A similar ques ...

Encountering the error message "This expression cannot be invoked" within a Typescript React Application

I'm working on separating the logic from the layout component in my Typescript React Application, but I suspect there's an issue with the return type of my controller function. I attempted to define a type to specify the return type, but TypeScr ...

Creating a dynamic columns property for Mat-Grid-List

Is it possible to create a Mat-Grid-List where the number of columns can be dynamically changed based on the width of the container? Here is an example: <mat-grid-list [cols]="getAttachmentColumns()" rowHeight="100px" style="width: 100%;"> <mat ...

Global Inertia Headers

How can I ensure that a custom header (Accept-Content-Language) is sent with every request, including Inertia manual visits? Below is the code snippet where I define and set the header: import axios from 'axios'; const lang = localStorage.getIt ...

Unable to bring in a TypeScript library that was downloaded from a GitHub fork repository

Currently, I am working on developing a GitHub app using the probot library. However, I have encountered an obstacle as outlined in this particular issue. It seems that probot does not offer support for ESM modules, which are crucial for my app to function ...

Tips for sending a function as a value within React Context while employing Typescript

I've been working on incorporating createContext into my TypeScript application, but I'm having trouble setting up all the values I want to pass to my provider: My goal is to pass a set of values through my context: Initially, I've defined ...

Issue with dynamically typed object properties in Typescript codebases

Check out this TypeScript code snippet: export type Mutation = (state: State, data: unknown) => void export type Mutations = { [key: string]: Mutation } private buildMutations(): Mutations { return { ['3']: (state, data) => ...