React Native SectionList Displaying Incorrectly

I have been trying to bind an array of objects to a SelectionList, and although it seems to be binding, each character is being rendered as an individual list item instead of a single item.

Take a look at my code snippet:

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

r: GetRecipesResponse is a list of objects that I am converting to an array. The issue with rendering can be seen on the right side in the above image.

interface States {
    response: GetRecipesResponse;
    globalItems: any[];
    isModalVisible: boolean;
    selectedItem: any;
    selectedItemUnit: any;
}

export class MatrixScreen extends BaseNetworkScreen<GetRecipesResponse, Props, States> {

    itemWidth: number = 100;
    itemMargin: number = 3;
    selectedItemsArray: any[];

    constructor(props: Props) {
        super(props);

        this.selectedItemsArray = [];

        this.state = {
            isLoading: false,
            response: null,
            globalItems: this.selectedItemsArray,
            isModalVisible: false,
            selectedItem: null,
            selectedItemUnit: null
        };
    }
}

renderSelectLists(r: GetRecipesResponse): any {

    var arr = [];
    for (var key in r.data.recipe) {
      arr.push(r.data.recipe[key].name);
    }

    let sections = []
    for (const key in this.state.globalItems) {
        if (this.state.globalItems.hasOwnProperty(key)) {
            sections.push({
                data: this.state.globalItems[key],
                key: key,
                unit: this.state.selectedItemUnit
            })
        }
    }

    return (
        <View style={{ flex: 1, flexDirection: 'row' }}>
            <View style={styles.addContainer}>

                <Text>Press To Add Item</Text>

                <SectionList

                    sections={[{ data: arr }]}
                    renderItem={({ item }) => <Text style={styles.SectionListItemS} onPress={this.loadMatrixModal.bind(this, item)}> {item} </Text>}
                    keyExtractor={(item, index: any) => index}
                />
            </View>
            <View style={styles.removeContainer}>
                <Text>Press To Remove Item</Text>
                <SectionList
                    sections={sections}
                    renderItem={({ item, index }) => <Text style={styles.SectionListItemS} onPress={this.removeSectionListItem.bind(this, index)}> {item} </Text>}
                    keyExtractor={(item, index: any) => item}
                />
            </View>
        </View>
    );
}

After defining "sections" and logging it out to the console, it displays as shown in the following image:

https://i.sstatic.net/00gMq.png

Update:

If I include

renderItem={({ item, index }) => <Text style={styles.SectionListItemS} onPress={this.removeSectionListItem.bind(this, index)}> {console.log(item)} {item} </Text>}

An interesting output is logged to the console, as depicted below:

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

Answer №1

The property you are trying to render is not being accessed correctly.

In order to display the information you want, you must access the data property of each item.

Therefore, you should make the following adjustment:

renderItem={({ item }) => <Text style={styles.SectionListItemS} onPress={this.loadMatrixModal.bind(this, item)}> {item.data} </Text>}

By changing { item } to { item.data }, you are specifically targeting the data property within the item object for rendering.

Answer №2

My approach to constructing the object was as follows:

const itemData = {name: itemName, quantity: itemQuantity};
const constructedObject = {items: [itemData]};

Once the object was created, I added it to an array and updated the globalItems state with the new array.

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

The function cannot be called on a type that does not have a callable signature. The specified type, 'number | Dispatch<SetStateAction<number>>', does not have any compatible call signatures

Currently, I am working on setting up state to be passed through context in React using hooks. However, when I attempt to use the dispatched state updater function, an error is thrown: Cannot invoke an expression whose type lacks a call signature. Type &a ...

How can I change an icon and switch themes using onClick in react js?

I have successfully implemented an icon click feature to change the colorscheme of my website (in line 21 and changeTheme). However, I also want the icon to toggle between FaRegMoon and FaRegSun when clicked (switching from FaRegMoon to FaRegSun and vice v ...

What is an improved method for defining a TypeScript type to store API method invocations?

Currently, I am exploring ways to enhance either GenericActionables or Items in a way that eliminates the need to manually add the API method name as a GenericActionables<"nameOfNewMethod"> to the Actionables type every time. Any suggesti ...

Building Silent Authentication in React Native with the help of Auth0: A Step-by-Step Guide

I am currently working on my first React Native app, and I have integrated Auth0 for authentication purposes. My goal is to implement silent authentication using refresh tokens. So far, I have attempted to use the checkSession() method but encountered an ...

Adding a method to an object with TypeScript: A step-by-step guide

In my current scenario, I am faced with a challenge where I need to test a function with a specific use of this. However, typescript poses constraints by either disallowing me from adding the method to the object, or if I define it as any, then my interfac ...

"Learn how to utilize Angular to showcase an array of strings and choose a specific value for

When working in HTML, I have the ability to set the option text and send the value like this: <select id="cars"> <option value="volvo">Volvo</option> <option value="saab">Saab</option> </select> After sending it ...

Issue with detecting undefined in a nested function using Typescript

Examining the code snippet provided below, focus on the test getter. Why is it that const name = this.person.name does not result in an error, while const processPerson = () => this.person.name does generate an error? interface Person { name: string; ...

Implementing conditional properties in Typescript based on the value of another property

Is it possible to make a property required in a type based on the presence of another property? Here's an example: type Parent = { children?: Child[]; childrenIdSequence: string[]; // This property should only be required when `children` is prov ...

Searching for MongoDB / Mongoose - Using FindOneById with specific conditions to match the value of an array inside an object nestled within another array

Although the title of this question may be lengthy, I trust you grasp my meaning with an example. This represents my MongoDB structure: { "_id":{ "$oid":"62408e6bec1c0f7a413c093a" }, "visitors":[ { "firstSource":"12 ...

My goal is to develop a secure login system with authentication on the Angular platform

login(data: any) { this.user.getUsers().subscribe( (users) => { const user = users.find((u) => u.username === data.username && u.userpassword === data.password); if (user) { // Valid username and password, ...

Getting Form Value in Component.ts with Angular 5

How can I incorporate an input form into my component while constructing a form? <div class="row"> <div class="col-md-6 offset-md-3 text-center> <h2> Login Form </h2> <form (ngSubmit)="OnSubmit(login.value,password.value)" #l ...

Angular Component Test Results in TypeError Error Failure

After defining a custom error class called CustomError: export class CustomError extends Error { constructor(message?: string) { super(message); Object.setPrototypeOf(this, CustomError.prototype); } } I want to throw instances of ...

Restrict or define the acceptable values for a key within an interface

In search of defining an interface that allows for specific range of values for the key. Consider this example: interface ComparisonOperator { [operator: string]: [string, string | number]; } The key can take on values such as >, >=, !=, and so ...

Using Angular 2 to round a calculated number within HTML

In the HTML code, there is a calculated number associated with Component1. Component1 serves as a tab page within a Bootstrap tab panel. Below is the HTML code with the tab panel: <div id="minimal-tabs" style="padding:75px;padding-top:60 ...

You cannot use ca.select(....).from function after the code has been minified

My Angular application utilizes squel.js and functions correctly in development mode. However, upon building the app for production and attempting to use it, I encounter the following error message: ca.select(...).from is not a function This error ref ...

Tips for evaluating the stickiness of a block within a cell when it adheres to a mat-header-cell

I am working with an Angular table and facing an issue. How can I make the span element in the cells of the first column stick to the sticky mat-header-row when scrolling down the table? My requirement is for the span element to stay attached to the lower ...

Transfer the data stored in the ts variable to a JavaScript file

Is it possible to utilize the content of a ts variable in a js file? I find myself at a loss realizing I am unsure of how to achieve this. Please provide any simple implementation suggestions if available. In my ts file, there is a printedOption that I w ...

Using TypeScript to define values with the placeholder "%s" while inputting an object as a parameter

One common way to decorate strings is by using placeholders: let name = "Bob"; console.log("Hello, %s.", name) // => Outputs: "Hello, Bob." I'm curious if there's a way to access specific values within an object being passed in without specif ...

What is the best way to combine a Signal containing an array of Signals in Angular using the merge(/mergeAll) operator?

When working in the world of rxjs, you have the ability to combine multiple Observables using the merge operator. If you have an array of Observables, all you need to do is spread that array into the merge operator like this: merge(...arrayOfObservables). ...

How can I utilize npm with the original source code instead of minified or bundled code?

I am looking to access npm and JavaScript (or TypeScript) 3rd party libraries directly from the source code. Similar to how I can make changes in Python libraries by going into their source code, I want to have the same capability with my JavaScript depen ...