Home > OS >  React Native : A simple DataTable in a FlastList, how to get a unique DataTable for each item?
React Native : A simple DataTable in a FlastList, how to get a unique DataTable for each item?

Time:12-24

I fetch my json data, I want to show it with a data table. The problem, my FlatList component create a new data table for each item but I want one DataTable for all my items.

I didn't find how to fix it. I share all the code here. Could you help me please ? Thank you

import React, { Component } from 'react';
import { StyleSheet, Text, View, FlatList, Dimensions, ActivityIndicator } from 'react-native';
import { DataTable } from 'react-native-paper';



export default class Bien extends Component {
    constructor(props) {
        super(props);

        this.state = {
        data: [],
        isLoading: true
        };
    }

    async getAll() {
        try {
            const response = await fetch('myJsonData');
            const json = await response.json();
            this.setState({ data: json.table });
        } catch (error) {
            console.log(error);
        } finally {
            this.setState({ isLoading: false });
        }
    }

    componentDidMount() {
        this.getAll();
    }

    renderItem = ({ item, index }) => {
        return (
            <View>
                <DataTable>
                    <DataTable.Header>
                        <DataTable.Title>Type</DataTable.Title>
                        <DataTable.Title>Ville</DataTable.Title>
                        <DataTable.Title numeric>Prix</DataTable.Title>
                    </DataTable.Header>

                    <DataTable.Row>
                        <DataTable.Cell>{item.Category}</DataTable.Cell>
                        <DataTable.Cell>{item.Ville}</DataTable.Cell>
                        <DataTable.Cell numeric>{item.Prix}</DataTable.Cell>
                    </DataTable.Row>
                </DataTable>

            </View>
        ); 
    };

    render() {
        const { data, isLoading } = this.state;
            return (
                <FlatList
                    data={data}
                    renderItem={this.renderItem}
                />
            );
    }
};

CodePudding user response:

Your FlatList is looping through for each item and creating a DataTable. You can instead wrap the Data.Row elements inside a FlatList.

<DataTable>
  <DataTable.Header>
    <DataTable.Title>Dessert</DataTable.Title>
    <DataTable.Title numeric>Calories</DataTable.Title>
    <DataTable.Title numeric>Fat</DataTable.Title>
  </DataTable.Header>

  <FlatList data={data} renderItem={_renderItem} />
</DataTable>

Full working example: https://snack.expo.dev/@tnr_c/scrollable-datatable

  • Related