Passing a GraphQL Array through React-Table - javascript

Hopefully this isn't too much of an overly basic question (though I think it might be). I've spent a few days trying to figure this out with no luck, I'm new at this.
I'm trying to use GraphQL with Shopify to generate a react-table with a bunch of information from the orders I receive on Shopify. I've gotten as far as being able to generate the data I want, but I can't seem to get it to generate a new row for each piece of data in the array.
As you can see from the image below, I just get '#1001', '#1002' in the same cell. Those are two different orders that I want on individual rows. I'm certain I need to use .map in a fashion and tell the react-table to push data, but nothing I've tried seems to work, and if it does it provides me with two individual rows- but no data in said rows.
I also think the way I'm telling the table to get the data is wrong. I need to use the accessors in my header section to define certain data that I receive from the query. Most of the accessors aren't correct barring orderNumber, Payment, customer. This is because I need to take information from lineItems and distribute it across multiple columns depending on the product. This question isn't really about this headache, but I just wanted to contextualise why some columns are missing accessors.
Here is my query:
import { gql } from '#apollo/client';
const wholesaleOrders = gql`
{
orders(first: 2, query: "tag:wholesale") {
edges {
node {
id
unpaid
fullyPaid
name
customer {
displayName
defaultAddress {
company
}
}
lineItems(first: 5) {
edges {
node {
quantity
name
}
}
}
}
}
}
}
`;
export default wholesaleOrders;
and here is my Table:
import React from 'react'
import styled from 'styled-components'
import { useTable } from 'react-table'
import { graphql, Query } from 'react-apollo';
import { gql, useQuery } from '#apollo/client';
import wholesaleOrders from './QueryData.js'
function Table({ columns, data }) {
// Use the state and functions returned from useTable to build your UI
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>
)
}
function DataTable() {
const columns = React.useMemo(
() => [
{
Header: 'Order',
columns: [
{
Header: 'Order',
accessor: 'orderNumber',
},
{
Header: 'Status',
accessor: 'payment'
},
{
Header: 'Customer',
accessor: 'customer'
},
],
},
{
Header: 'Wholesale 2kg',
columns: [
{
Header: 'EST',
accessor: 'lineItems'
},
{
Header: 'TB'
},
{
Header: 'BB'
},
{
Header: 'OTHER'
},
],
},
{
Header: 'Retail and Misc.',
columns: [
{
Header: '250g'
},
{
Header: 'Tea/Chocolate'
},
{
Header: 'Equipment'
},
{
Header: 'After Hours'
},
{
Header: 'Notes'
},
],
},
],
[]
)
return (
<Query
query={wholesaleOrders}>
{({ data, loading, error }) => {
if (loading) return <div>Loading…</div>;
if (error) return <div>{error.message}</div>;
console.log(data);
return (
<Table
data={[{orderNumber: data.orders.edges.map(({node}) => node.name )}]}
columns={columns}
defaultPageSize={10}
/>
);
}}
</Query>
)
}
export default DataTable;
and here is the result:
Result
Apologies for how verbose this is, I just wanted to cover all bases.
Thanks!

Nevermind, moron figured it out:
return (
<Query
query={wholesaleOrders}>
{({ data, loading, error }) => {
if (loading) return <div>Loading…</div>;
if (error) return <div>{error.message}</div>;
console.log(data);
return (
<Table
data={data.orders.edges.map((order) => {
return (
{
orderNumber: order.node.name,
payment: order.node.fullyPaid,
customer: order.node.customer.displayName,
});
})}
columns={columns}
defaultPageSize={10}
/>
);
}}
</Query>
)
}
Result
Days, days of trying to figure this out and I figure out after I post the question.

Related

Using react-table to populate a table based on a user. When I change the user on the page it renders infinitely and react errors out

So I have a user drop down menu that allows a person to impersonate a user to get a list of buckets. If you pick a different user it then makes an api call to then get a new list of buckets based upon that user. I am using react-table to create a table with information about the user's buckets. I can change the user on the other pages and the user gets updated and nothing explodes. But if I do it on the bucket page, it returns this:
The API call which happens in the parent component of my bucketTable component in the useEffect hook and that is tied to the user that I drop down from the app.js. The API call fires off and returns a list of buckets which I then pass down to my bucketTable component which then takes it and inserts it into a react-table.
I have an onChange event that bubbles up to App.js from my navbar and then drop the selected user down to the buckets page. Which then does an API call using useEffect which is then tied to the user field that I am passing around.
bucketTable.js
so the issue is that when I change the userDropdown on the navbar which then updates that value in the buckets.js component to get the list of buckets, this table page gets overwhelmed. I don't understand why I see my use effect is firing only when user is fired. I have done console.log statements and see that it only gets fired when I change it once, but this happens. This makes me think that something is rerendering over and over again causing this issue. Please help been pulling my hair out on this and I can provide more details upon request.
EDIT:
So when I change the user ON the bucket page which renders the bucketTable component I see that the bucket Table component is being rerendered a billions times...still looking into this will update when I have more information.
this is my bucketTable.js which is being rendered a TON when I change the user.
import "../index.css";
import { useTable } from "react-table";
const BucketTable = ({ buckets }) => {
console.log('BucketTable Rendered')
const data = []
const columns = [
{
Header: "Bucket Name",
accessor: "bucket",
},
{
Header: "Created By",
accessor: "created_by",
},
{
Header: "Storage Label",
accessor: "storage_label",
},
{
Header: "Zone",
accessor: "zone",
}
];
// Must only get the array cleansing of objs
buckets.buckets.forEach((x) => data.push(x));
console.log(data)
const { getTableProps, getTableBodyProps, headerGroups, rows, prepareRow } =
useTable({
columns,
data
});
return (
<>
<table {...getTableProps()}>
<thead>
{headerGroups.map((headerGroup) => (
<tr {...headerGroup.getHeaderGroupProps()}>
{headerGroup.headers.map((column) => (
<th {...column.getHeaderProps()}>{column.value}</th>
))}
</tr>
))}
</thead>
<tbody {...getTableBodyProps()}>
{rows.map((row) => {
prepareRow(row);
return (
<tr {...row.getRowProps()}>
{row.cells.map((cell) => {
return (
<td {...cell.getCellProps()}>{cell.value}</td>
);
})}
</tr>
);
})}
</tbody>
</table>
</>
);
};
export default BucketTable;
buckets.js which calls the bucketTable.js component
import { useEffect, useState } from "react";
import BucketList from "../Components/BucketList";
import useCollapse from "react-collapsed";
import { ToastContainer, toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
import * as AiIcons from "react-icons/ai";
import BucketTable from "../Components/BucketTable";
// TODO: Shift from cards to table
const Buckets = ({ user }) => {
const [bucketList, getBuckets] = useState(null);
const { getCollapseProps, getToggleProps, isExpanded } = useCollapse();
const [selectedACL, setValue] = useState("private");
const callGetBuckets = () => {
console.log("callGetBuckets Called")
const headers = {
"Content-Type": "application/json",
user: user,
};
notify("loading");
fetch("http://localhost:5000/rest/v1/buckets", { headers })
.then((res) => {
return res.json();
})
.then((data) => {
console.log('fired off?')
getBuckets(data);
notify("dismiss");
});
};
useEffect(() => {
console.log("useEffect fired")
callGetBuckets();
}, [user]);
const notify = (type) => {
switch (type) {
case "success":
toast.success("Bucket Created", {
toastId: "Success",
});
break;
case "fail":
toast.error("Bucket Creation Failed", {
toastId: "fail",
});
break;
case "loading":
toast.loading("Loading...", {
toastId: "loading",
});
break;
case "dismiss":
toast.dismiss();
break;
default:
}
};
const handleSubmission = (e) => {
e.preventDefault();
const requestOptions = {
method: "POST",
headers: { "Content-Type": "application/json", user: user },
body: JSON.stringify({
bucket: e.target.Name.value,
storage_label: e.target.StorageLabel.value,
acl: selectedACL,
}),
};
fetch("http://localhost:5000/rest/v1/bucket/create", requestOptions).then(
(res) => {
if (res.ok) {
notify("success");
console.log('fired off as well')
callGetBuckets();
} else notify("fail");
}
);
};
return (
<div>
<ToastContainer theme="theme" />
<div className="content">
<h2 className="bucketHeader">Buckets</h2>
<div>
<p>Returns a list of buckets that a user has access to view.</p>
</div>
<div className="collapsible">
<div className="header" {...getToggleProps()}>
Create Bucket
<span>
{isExpanded ? (
<AiIcons.AiOutlineArrowUp />
) : (
<AiIcons.AiOutlineArrowDown />
)}
</span>
</div>
<div {...getCollapseProps()}>
<div className="content-collapsible">
<form className="createBucketForm" onSubmit={handleSubmission}>
<label className="collapsible-label">
Name:
<input type="text" name="Name" />
</label>
<label className="collapsible-label">
Storage Label:
<input type="text" name="StorageLabel" />
</label>
<div className="dropDownForm">
<label className="collapsible-label">
ACL:
<span className="dropdown">
<label className="dropLabel">
<select
value={selectedACL}
onChange={(e) => setValue(e.target.value)}
>
<option value="private">private</option>
<option value="public-read">public-read</option>
<option value="public-read-write">
public-read-write
</option>
<option value="authenticated-read">
authenticated-read
</option>
</select>
</label>
</span>
</label>
</div>
<div>
<input className="formSubmit" type="submit" value="Submit" />
</div>
</form>
</div>
</div>
</div>
{bucketList && <BucketTable buckets={bucketList} />}
</div>
</div>
);
};
export default Buckets;
The answer for this was to move the const columns out of the component file. I moved it into its own file and imported it to the parent component then dropped it down as a prop and everything worked fine from there. THe reasoning I am still baffled as to why that happened. I still had issues when I imported it directly to the table component but when I brought the columns in as a prop it fixed itself. But that was the fix for the infinite rendering.
const columns = [ { Header: "Bucket Name", accessor: "bucket", }, { Header: "Created By", accessor: "created_by", }, { Header: "Storage Label", accessor: "storage_label", }, { Header: "Zone", accessor: "zone", } ];

react-table v7 no data displayed

Total noob here,
I was adapting the following tutorial (' https://www.youtube.com/watch?v=hson9BXU9F8&t=925s&ab_channel=Codevolution ') for my personal project, however my table does not show any data, I have tried comparing my project to the reference and even copying directly but i don't get any errors so its very difficult to pinpoint where I messed up.
TABLE COMPONENT
import React, { useMemo } from 'react'
import { useTable } from 'react-table'
import MOCK_DATA from './MOCK_DATA.json'
import { COLUMNS } from './columns'
import './table.css'
export const BasicTable = () => {
const columns = useMemo(() => COLUMNS, [])
const data = useMemo(() => MOCK_DATA, [])
const {
getTableProps,
getTableBodyProps,
headerGroups,
rows,
prepareRow
} = useTable({
columns,
data
})
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 => {
prepareRow(row)
return (
<tr {...row.getRowProps()}>
{row.cells.map(cell => {
return <td {...cell.getCellProps()}>{cell.render('Cell')}</td>
})}
</tr>
)
})}
</tbody>
</table>
</>
)
}
COLUMNS COMPONENT
export const COLUMNS = [
{
//nombra la columna, se le puede poner cualquie nombre
Header : 'id',
//determina el elemento del JSON a acceder
accesor: "id",
disableFilters: true,
sticky: 'left'
},
{
Header : 'nombre_usuario',
accesor: 'nombre_usuario'
},
{
Header : 'correo_usuario',
accesor: 'correo_usuario'
},
{
Header : 'Rol_usuario',
accesor: 'rol_usuario'
},
{
Header : 'Estado_usuario',
accesor: 'estado_usuario'
},
{
Header : 'ident_usuario',
accesor: 'id'
},
]```
MOCK JSON EXAMPLE
[{"id":1,"nombre_usuario":"Skipton Noquet","pw_usuario":"r7ND2xcYb","correo_usuario":"snoquet0#naver.com","rol_usuario":"adipiscing","estado_usuario":"phasellus","ident_usuario":"937"}]
here is the repo from the tutorial i have been following, it works perfectly (it has an older version of react table, I tried it out and it didn't work either):
https://github.com/gopinav/React-Table-Tutorials.git
Use page instead of rows
{page.map(row => {...}

How can I render API data into separate tables based on the value in React?

I'm trying to create a simple NBA boxscore web app in React, but I am having trouble rendering the API data into separated tables for each game. I am trying to create separate tables with its own headers for each game based on the gameID value from the API. How can I achieve this?
import React, { Fragment } from 'react';
import ScoreCards from './ScoreCards';
const ScoreCardData = ({ gameStats }) => {
return(
<table>
<tbody>
<tr>
<td>gameID</td>
<td>Players</td>
<td>FGM/A FG%</td>
<td>FTM/A FT%</td>
<td>3PTM</td>
<td>PTS</td>
<td>REB</td>
<td>AST</td>
<td>ST</td>
<td>BLK</td>
<td>TO</td>
</tr>
{Object.keys(gameStats).map((gameData, i) => {
return(
<Fragment>
<tr key={i}>
<td>{gameStats[gameData].game.id}</td>
</tr>
</Fragment>
)
})
}
</tbody>
</table>
)
};
export default ScoreCardData;
Here is the code where I try to render the API data. I'm able to get a list of all the game ID's in one table, but I want to separate them according to gameID value so that I can display each table as a separate game. I also want to have the header row with all the stat names to be displayed for each table.
I'm basically just trying to create a simple NBA box score website, but I am having trouble actually rendering the data into a box score format. This is my first web application that I am creating, so I am very lost. Any help would be appreciated.
Fullsize Image
Please try like this, if want to display separate table based on game id, we need to group the data first by game.id then loop through original gameStats data via Object.keys.
Demo link: https://codesandbox.io/s/8yjwk4nzv2
import groupBy from "lodash.groupby";
const ScoreTable = props => {
console.log("props.gameStats ", props.gameStats);
return (
<table>
<tbody>
<tr>
<td>gameID</td>
<td>Players</td>
<td>FGM/A FG%</td>
<td>FTM/A FT%</td>
<td>3PTM</td>
<td>PTS</td>
<td>REB</td>
<td>AST</td>
<td>ST</td>
<td>BLK</td>
<td>TO</td>
</tr>
{props.gameStats.map((gameData, i) => {
return (
<Fragment>
<tr key={i}>
<td>{gameData.game.id}</td>
</tr>
</Fragment>
);
})}
</tbody>
</table>
);
};
const ScoreCardData = props => {
return Object.keys(props.gameStats).map((item, i) => {
return <ScoreTable gameStats={props.gameStats[item]} />;
});
};
const gameStats = [
{
game: { id: 47820 },
player: {},
stats: {},
team: { id: 57, abbreviation: "POR" }
},
{
game: { id: 47820 },
player: {},
stats: {},
team: { id: 57, abbreviation: "POR" }
},
{
game: { id: 5000 },
player: {},
stats: {},
team: { id: 57, abbreviation: "POR" }
},
{
game: { id: 5000 },
player: {},
stats: {},
team: { id: 57, abbreviation: "POR" }
},
{
game: { id: 6000 },
player: {},
stats: {},
team: { id: 57, abbreviation: "POR" }
}
];
const groupedData = groupBy(gameStats, "game.id");
console.log("groupedData ", groupedData);
If gameStats is an array of objects, and each object is a unique game, you can render a table per unique game by moving all of your logic within the map function. This is assuming you want an actual <table>...</table> per game.
import React, { Fragment } from 'react';
import ScoreCards from './ScoreCards';
const ScoreCardData = ({ gameStats }) => {
return(
{Object.keys(gameStats).map((gameData, i) => {
return (
<Fragment>
<table>
<tbody>
<tr>
<th>gameID</th>
<th>Players</th>
<th>FGM/A FG%</th>
<th>FTM/A FT%</th>
<th>3PTM</th>
<th>PTS</th>
<th>REB</th>
<th>AST</th>
<th>ST</th>
<th>BLK</th>
<th>TO</th>
</tr>
<tr key={i}>
<td>{gameStats[gameData].game.id}</td>
...
<td>{gameStats[gameData].game.to}</td>
</tr>
</tbody>
</table>
</Fragment>
)
})
})
};
export default ScoreCardData;

React-Table doesn't show data from firebase, but shows identical, handmade data

I've been trying to make a locker organization / assignment app for a school project, and I've seen to hit a roadblock at the displaying of the firebase database. I found React-Table, which seemed like a good way to display the data, but I've had some issues actually displaying the data. When I run the app, it says that no rows are found.
Below is the code for my LockTable.js component.
import React, { Component } from 'react';
import firebase from 'firebase/app';
import { auth } from '../firebase';
import 'firebase/database';
//import { database } from '../firebase';
import ReactTable from "react-table";
import 'react-table/react-table.css';
class LockTable extends Component{
constructor(props){
super(props);
}
render(){
const database = firebase.database().ref("LockerList");
const data1 = [];
database.on('value',snapshot => {
//Read each item in LockerList
//Store it in a temporary array
snapshot.forEach(childSnapShot => {
//childSnapShot.key is the name of the data
//childSnapShot.val() is the value of the data
const Locker = {
LockerNumber : childSnapShot.key.toString(),
Available : childSnapShot.val().Available,
StudentName : childSnapShot.val().StudentName,
StudentNumber : childSnapShot.val().StudentNumber.toString() ,
Period : childSnapShot.val().StudentPeriod.toString(),
Teacher : childSnapShot.val().Teacher,
};
data1.push(childSnapShot.val());
});
});
const columns = [
{
Header: 'Locker Number',
accessor: 'LockerNumber'
}, {
Header: 'Available',
accessor: 'Available',
}, {
Header: 'Student Name',
accessor: 'StudentName',
}, {
Header: 'Student Number',
accessor: 'StudentNumber',
}, {
Header: 'Period',
accessor: 'Period',
}, {
Header: 'Teacher',
accessor: 'Teacher',
} ];
console.log(data1);
return(
<div>
<ReactTable
data={data1}
columns={columns}
/>
</div>
);
}
}
export default LockTable;
This is what my firebase database looks like
This is what the data I read from firebase looks like
To test React-Table out, I made a StackBlitz with handmade variables rather than variables read from firebase.
https://stackblitz.com/edit/react-table-help
If you open the console, you can see that the data from the StackBlitz version is the exact same as the data from my version, yet, the StackBlitz version is displaying the data, while my version is not.
Does anyone know why my version doesn't work? Any help would be appreciated!
The render method can only handle synchronous logic. The firebase database logic is asynchronous, so to use it you can put it in componentDidMount instead and put the data in the component state when you get a snapshot.
Example
class LockTable extends Component {
state = { data: [] };
componentDidMount() {
const database = firebase.database().ref("LockerList");
database.on("value", snapshot => {
const data = [];
snapshot.forEach(childSnapShot => {
const locker = {
LockerNumber: childSnapShot.key.toString(),
Available: childSnapShot.val().Available,
StudentName: childSnapShot.val().StudentName,
StudentNumber: childSnapShot.val().StudentNumber.toString(),
Period: childSnapShot.val().StudentPeriod.toString(),
Teacher: childSnapShot.val().Teacher
};
data.push(locker);
});
this.setState(prevState => {
return { data: [...prevState.data, ...data] };
});
});
}
render() {
const columns = [
{
Header: "Locker Number",
accessor: "LockerNumber"
},
{
Header: "Available",
accessor: "Available"
},
{
Header: "Student Name",
accessor: "StudentName"
},
{
Header: "Student Number",
accessor: "StudentNumber"
},
{
Header: "Period",
accessor: "Period"
},
{
Header: "Teacher",
accessor: "Teacher"
}
];
return (
<div>
<ReactTable data={this.state.data} columns={columns} />
</div>
);
}
}

How to map over an object which has a unique id for each object values and return the values to a React component

I am working on a redux project where I want to retrieve the values stored in API server.I want to store the data from the API in my redux store and then retrieve the values and display it in my react component.The data in the API server is in the form of an object but has a unique id for each value.So,in my case, the data is a list of posts.So, each post has a unique id and has all the other details like timestamp,post-title,post-author etc.This is how the default data from the API for posts looks like:
const defaultData = {
"8xf0y6ziyjabvozdd253nd": {
id: '8xf0y6ziyjabvozdd253nd',
timestamp: 1467166872634,
title: 'Udacity is the best place to learn React',
body: 'Everyone says so after all.',
author: 'thingtwo',
category: 'react',
voteScore: 6,
deleted: false,
commentCount: 2
},
"6ni6ok3ym7mf1p33lnez": {
id: '6ni6ok3ym7mf1p33lnez',
timestamp: 1468479767190,
title: 'Learn Redux in 10 minutes!',
body: 'Just kidding. It takes more than 10 minutes to learn technology.',
author: 'thingone',
category: 'redux',
voteScore: -5,
deleted: false,
commentCount: 0
}
}
Note: The "id" which is a random number here(like "8xf0y6ziyjabvozdd253nd") becomes an integer, i.e the 1st post gets the id 1 ,the 2nd gets 2.
So, I am able to store the data from posts API in my redux "Store". And I converted the posts object into an array(as we cannot map over an object) because I want to map over this array and show the data in my React component.But,I am not able to see the result of the array in my component,maybe that's because it has an id before each object in the array.This is how I am trying to map over the arrayand I do not get any error,but I do not see the results from the object in component.My component file looks like this:
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { fetchPosts } from '../actions';
import _ from 'lodash';
class PostsIndex extends Component {
componentDidMount() {
this.props.dispatch(fetchPosts())
.then(() => {
this.setState({
loading : false
});
// console.log(this.props.posts.posts[0])
})
}
render() {
// console.log(this.props.posts.posts)
const obj = this.props.posts.posts;
let arr;
if (obj) {
arr = Object.values(obj); //Converting an Object into an array
}
console.log(arr); //returns the converted array from an object
return(
<div>
{
arr ?
<div>
{ arr.map(post =>
{
<div>
{post.title}
</div>
})
}
</div>
:
<div>
No Data
</div>
}
</div>
);
}
}
function mapStateToProps(state) {
return { posts: state.posts };
}
export default connect(mapStateToProps)(PostsIndex);
And when I console.log my state,the converted array looks like this:
When expanded looks like:
I want to retrieve almost all of the values from the above array.Can anyone please show me how to get the data from the array and map over the array to show the values in my React component?
You can keep your data as an object, and use Object.keys to get an array of keys, map over the keys, and use the keys to access nested objects. If you don't know the shape of your data source, you could use recursion.
Here is a working code sandbox example where I've taken your data source and turned it into a table to illustrate how to do so.
Here is the code:
import React from 'react';
import { render } from 'react-dom';
import Hello from './Hello';
const defaultData = {
"8xf0y6ziyjabvozdd253nd": {
id: '8xf0y6ziyjabvozdd253nd',
timestamp: 1467166872634,
title: 'Udacity is the best place to learn React',
body: 'Everyone says so after all.',
author: 'thingtwo',
category: 'react',
voteScore: 6,
deleted: false,
commentCount: 2
},
"6ni6ok3ym7mf1p33lnez": {
id: '6ni6ok3ym7mf1p33lnez',
timestamp: 1468479767190,
title: 'Learn Redux in 10 minutes!',
body: 'Just kidding. It takes more than 10 minutes to learn technology.',
author: 'thingone',
category: 'redux',
voteScore: -5,
deleted: false,
commentCount: 0
}
}
const TableHeader = ({ fields }) => (
<thead>
<tr>
{
fields.map( field => <th key={ field }>{ field }</th>)
}
</tr>
</thead>
);
const TableBody = ({ data }) => (
<tbody>
{
Object.keys(data).map(
datum =>
<tr>
{
Object.keys(data[datum]).map(
field => <td>{data[datum][field]}</td>
)
}
</tr>
)
}
</tbody>
);
const App = () => (
<table>
<TableHeader fields={ Object.keys(defaultData[Object.keys(defaultData)[0]]) } />
<TableBody data={defaultData} />
</table>
);
render(<App />, document.getElementById('root'));
You need map your data. Something like this:
<div>
<ul>
{props.incomingDataArray.map((singleArrayItem, index) => {
return (
<li key="list + index">{singleArrayItem.commentCount}</li>
<li key="list + index">{singleArrayItem.timestamp}</li>
)
})
}
</ul>
<div>
you forgot return inside your map.
render() {
const obj = this.props.posts.posts;
let arr;
if (obj) {
arr = Object.values(obj); //Converting an Object into an array
}
return (
<div>
{ arr ?
<div>
{ arr.map(post => {
return (
<div key={post.id}>
{post.title}
</div>
)
})
}
</div> :
<div>
No Data
</div>
}
</div>
);
}
or, alternatively, drop the curly braces with a oneliner:
arr.map(post => (<div key={post.id}>
{post.title}
</div>
)
)
and don't forget the key attribute.
I also suggest you abstract way your dumb components. It'll make your code more readable.

Categories