How display data from firebase properly aligned in a table.? Using React Native.?

Viewed 64

I am trying to display object names and keys in the table through the map function in alignment. But only object data names are displayed in an alignment, object key values are not displayed aligned. I need help.!

App.js

import React, { Component } from 'react';
import { Text, View, ImageBackground, StyleSheet, ScrollView } from 'react-native';
import CustomHeader from '../CustomHeader';
import firebase from '../../database/firebase';

import { DataTable } from 'react-native-paper';

var categories = [];
var categories1 = [];
var data;
// var key;
// var data;
var count = 0;

export default class Bus_Schedule extends Component {
    constructor(props) {
        super(props);
        this.state = {
            dataArray: {},
            arrayList: [],
            menu1:[],
            menu2: [],
          };

    }
    componentDidMount() {
        // firebase.database().ref('Schedule/Route-01/').on('value', querySnapShot => {
        //    data = querySnapShot.val() ? querySnapShot.val() : {};

        //    console.log("Data submit")
        //   let todoItems = {...data};
        //   console.log(todoItems);
        //   this.setState({
        //     dataArray: todoItems,
        //   });
        // });



        ///

        // var data1 = [];
        // console.log("letter send");
        // firebase.database().ref('Schedule/Route-01/').once("value").then(snapshot => {
        //   var data1 = Object.keys(snapshot.val());
        //   console.log(data1);
          
        // })
        
        

        firebase.database().ref('Scheduleinfo/-Md0XP_If-zG3F3qnNmv/').once('value').then(function(snapshot) {

          console.log("        Again");

          // this.setState({
          //   menu1: snapshot.val()
          // })

          // const categories = []
          // var categories1 = []

          snapshot.forEach(function(snap) {
             const item = snap.val();
             categories.push({ key: snap.key, data: snap.val() });

            const item1 = snap.key;
              categories1.push(item1);
              count++;

            
              // Array1 = item;
              // console.log(Array1);
              // let item1 = snap.key ? snap.key : {};
              // Array2 = item1;
              
             
                 
          });
          console.log(count);

          /// For object Values
        //   console.log("Values");
        //  console.log(categories);
        //   this.setState( {    //PASSING VARIABLE TO STATE
        //     menu1 :categories
        // })
        // console.log(this.state.menu1);
         /// For object Names
         console.log("Names");
        console.log(categories1);
          this.setState( {    //PASSING VARIABLE TO STATE
            menu2 :categories1
        })
        console.log(this.state.menu2);


      //  if (categories1 === "123")
      //  {
      //    console.log("SRK");
      //  } 
      //  else{
      //   console.log("No data");

      //  }

      //   categories1.map(x => {
      //   if (x === '123' || x === '456'){
      //    console.log(x);
      //   }else{
      //     console.log("nothing");
      //   }
      // })



      /// Use this method to login user ///
     /// With State Array ///
     
     const name = "AlFateh";
      for(let i =0 ; i< count; i++)
      {
        if(this.state.menu2[i] == name)
        {
          console.log(name);
        }
        // console.log('nothing');
      }
    


       
        
          
         
     }.bind(this));

      }


      empty()
      {
        categories1 = [];
        categories = [];

      }
      
    render() {
        let todosKeys = Object.keys(this.state.dataArray);
        
        return (
            <View
            style={styles.container}>
            <CustomHeader title="Bus Schedule" navigation={this.props.navigation} />

            <DataTable style={{ top: -12 }}>
              <DataTable.Header style={{ backgroundColor: '#F7EA6D' }}>
                <DataTable.Title style={{ justifyContent: 'center', alignItems: 'center' }}><Text style={{ fontSize: 20, fontWeight: "bold" }}>Route-1</Text></DataTable.Title>
              </DataTable.Header>

              <DataTable.Header style={{ backgroundColor: '#F7EA6D' }}>
              <DataTable.Title style={{ marginLeft:35 }}><Text style={{ fontSize: 20, fontWeight: "bold" }}>PLACE                DEPT.TIME</Text></DataTable.Title>
            </DataTable.Header>
              

              {
                categories.map(({ key, data }, key1) => (
                  <View style={{ backgroundColor: "#D1FDFF",}} key={key1} id={key1}>
                    <DataTable.Row>
                      <DataTable.Cell style={{ marginLeft: 50, }}>
                        <Text style={{ fontSize: 15, fontWeight: "bold" }} key={key1} id={key1}>
                          {key}
                        </Text>
                                    
                        <View
                          style={{
                          
                            alignItems:'center',
                            justifyContent:'center',
                            alignSelf:'center',
                            flexDirection:'column',
                            
                          }}
                          key={`key_1`}
                          id={`key_1`}
                        >
                          <Text key={`key_2`} id={`key_2`} style={{paddingLeft: 34, marginLeft: 100, textAlign: 'center', fontSize: 15, fontWeight: "bold"}}>
                            {data}
                          </Text>
                        </View>
                      </DataTable.Cell>
                    </DataTable.Row>
                  </View>
                ))
              }

            </DataTable>

           
          
            
            {this.empty()}
          </View>

        );

    }
}



const styles = StyleSheet.create({
    container: {
        backgroundColor: '#FEF9E7',
        flex: 1,
        
    },

    appButtonText: {
        fontSize: 15,
        color: "#fff",
        fontWeight: "bold",
        alignSelf: "center",
        textTransform: "uppercase"
    }

});

I am trying to display object names and keys in the table through the map function in alignment. But only object data names are displayed in an alignment, object key values are not displayed aligned. I need help.!

Output where object key value are not aligned

2 Answers

You should put key and data in a separated DataTable.Cell

<DataTable.Row>
  <DataTable.Cell>{key}</DataTable.Cell>
  <DataTable.Cell>{data}</DataTable.Cell>
</DataTable.Row>

do the same with the titles

<DataTable.Header>
  <DataTable.Title>PLACE</DataTable.Title>
  <DataTable.Title>DEPT.TIME</DataTable.Title>
</DataTable.Header>

and modify your styles in these components

@Gustavo Perez Machado, Your answer was great, but it gave a unique key prop error.!! But I have solved it through another solution by putting {data} array in a view with a unique prop key id to avoid any style non-alignment.

    <DataTable style={{ top: -12 }}>
      <DataTable.Header style={{ backgroundColor: '#F7EA6D' }}>
      <DataTable.Title style={{ justifyContent: 'center', alignItems: 'center' }}><Text style={{ fontSize: 20, fontWeight: "bold" }}>Route-1</Text></DataTable.Title>

      </DataTable.Header>

      <DataTable.Header style={{ backgroundColor: '#F7EA6D' }}>

      <DataTable.Title style={styles.aligntable1}><Text style = {{fontWeight:"bold",fontSize:15}}>PLACE</Text></DataTable.Title>
      <DataTable.Title style={styles.aligntable2}><Text style = {{fontWeight:"bold",fontSize:15}}>DEPT.TIME</Text></DataTable.Title>            
      
      </DataTable.Header>
      

      {
        categories.map(({ key, data }, key1) => (
          <View style={{ backgroundColor: "#D1FDFF",}}  key={key1} id={key1}>
            <DataTable.Row >
              <DataTable.Cell style={styles.aligntable1} >
              <Text key={key1} id={key1}>{key}</Text>
                  
                </DataTable.Cell>
                <DataTable.Cell style={styles.aligntable2} key={`key_2`} id={`key_2`}> 
                <View
                key={`key_1`}
                id={`key_1`}>
                <Text key={`key_2`} id={`key_2`}>{data}</Text> 
                </View>      
                  
                
              </DataTable.Cell>
            </DataTable.Row>
          </View>
        ))
      }

    </DataTable>
Related