I was new in React, and I am confusing about iterating props data in JSX.
Assume the this.props.data is
[
[
"2017-1",
{
title: "title1"
describe: "des1"
}
],
[
"2017-2",
{
title: "title2"
describe: "des2"
}
],...
]
How do I iterate data in table?
I was hoping it will render some kind of like this
<tbody>
<tr>
<td>2017-1</td>
<td>title1</td>
<td>des1</td>
</tr>
<tr>
<td>2017-2</td>
<td>title2</td>
<td>des2</td>
</tr>
...
</tbody>
I would map it. I'm assuming that the format will always be the same (out of laziness).
(Please do not run the snippet, it is only for formatting)
Fiddle: https://jsfiddle.net/gL8drpyd/1/
var data = [
[
"2017-1",
{
title: "title1"
describe: "des1"
}
],
[
"2017-2",
{
title: "title2"
describe: "des2"
}
]
];
let rows = data.map( (item) =>
(
<tr>
<td>{item[0]}</td>
<td>{item[1].title}</td>
<td>{item[1].describe}</td>
</tr>
)
);
// put this in the <tbody> in render
<tbody>
{rows}
</tbody>
Related
I have a JavaScript object in which I am trying to render as a table, though I am unable to figure out how to access each individual array.
Here is a sample of the object (defLogTable):
{
"headings": [
"Item",
"Equip Tag",
"Ref#",
"Description",
"Corrective Action Taken or Date Completed"
],
"values": [
[
1,
"RTU-1",
1,
"This did not work",
"Make it Work"
],
[
2,
"EF-1",
2,
"This also didn't work",
"Make this one work too"
]
]
}
Each 'values' array corresponds to a row in the table.
And What I have tried:
<table className="def-tbl">
<tbody>
{console.log(defLogTable)}
{defLogTable.headings.map(heading => (
<th>{heading}</th>
))}
</tbody>
</table>
Error: TypeError: Cannot read properties of undefined (reading 'headings')
Any help is appreciated!!
Use a nested map to render each row in the values property.
<table className="def-tbl">
<thead>
<tr>
{defLogTable.headings.map(heading => (
<th>{heading}</th>
))}
</tr>
</thead>
<tbody>
{defLogTable.values.map(row => (
<tr>
{row.map(cell => (
<td>{cell}</td>
))}
</tr>
))}
</tbody>
</table>
I'm having trouble with displaying my json data correctly. I want to get each products and place them into it's own row.
The problem now is that it places all the data of for example the value "name" into one table row instead of multiple rows.
This is my json data
{
id: "FVFkkD7s8xNdDgh3zAyd",
name: "AlperKaffe",
products: [
{
id: "0cfBnXTijpJRu14DVfbI",
name: "Første Kaffe",
price: "1",
size: "small",
quantity: "20 ml"
},
{
id: "JQadhkpn0AJd0NRnnWUF",
name: "Anden Kaffe",
price: "2",
size: "Medium",
quantity: "25 ml"
},
{
id: "UwHHdH8bFxbVHkDryeGC",
name: "kaffeeen",
price: "300",
size: "Small",
quantity: "23 ml"
},
{
id: "WiX5h0wFMNkCux9cINYq",
name: "kaffe modal",
price: "230",
size: "Medium",
quantity: "39 ml"
},
this is my Js file which gets the json data. As you can see i'm only working with the "name" value for now
// Jquery getting our json order data from API
$.get("http://localhost:8888/products", (data) => {
let rows = data.map(item => {
let $clone = $('#frontpage_new_ordertable tfoot tr').clone();
let productsName = item.products.map(prod => `${prod.name}`);
$clone.find('.name').html(productsName);
return $clone;
});
// appends to our frontpage html
$("#frontpage_new_ordertable tbody").append(rows);
});
this is my html file
<body>
<table id="frontpage_new_ordertable">
<tbody>
<tr>
<th>Name</th>
<th>Price</th>
<th>Size</th>
<th>Quantity</th>
<th></th>
</tr>
</tbody>
<tfoot>
<tr>
<td class="name"></td>
<td class="price"></td>
<td class="size"></td>
<td class="quantity"></td>
<td class="buttons"></td>
</tr>
</tfoot>
</table>
<script src="./itemPage.js"></script>
</body>
you must replace
let rows = data.map(item => {
to
let rows = data.products.map(item => {
and
let productsName = item.products.map(prod => `${prod.name}`);
to
let productsName = item.name;
https://jsfiddle.net/ab7t1vmf/3/
The issue in your JS snippet seems to be let rows = data.map(item => { ...
From what you describe, the JSON data is comprised of 3 keys:
id
name
products
You cannot execute a map function directly on a Javascript Object, this function requires an array.
Looking a bit more at your code, I understand you need to display each product on its own row. Thus, you would need to use the map function on data.products which contains an array (of products).
let rows = data.products.map(item => {
// ...
$clone.find('.name').html(item.name);
// ...
// ...
});
Reference: https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Array/map
I am facing an issue to order the columns of a fetched API data horizontally. I am trying to print the data fetched from an API into a table. Anyhow the rows are well printed horizontally, but the function that I used for rows this.state.data.map() doesn't function in the same way for the columns. I think it's ES6 standard, but I am not sure. Here is my printed issue.
Here is my code sample:
class App extends React.Component
{
constructor()
{
super();
this.state = {
rows: [],
columns: []
}
}
componentDidMount()
{
fetch( "http://ickata.net/sag/api/staff/bonuses/" )
.then( function ( response )
{
return response.json();
} )
.then( data =>
{
this.setState( { rows: data.rows, columns: data.columns } );
} );
}
render()
{
return (
<div id="container" className="container">
<h1>Final Table with React JS</h1>
<table className="table">
<thead> {
this.state.columns.map(( column ) => (
<tr>
<th>{column[0]}</th>
<th>{column[1]}</th>
<th>{column[2]}</th>
<th>{column[3]}</th>
</tr>
) )}
</thead>
<tbody> {
this.state.rows.map(( row ) => (
<tr>
<td>{row[0]}</td>
<td>{row[1]}</td>
<td>{row[2]}</td>
<td>{row[3]}</td>
</tr>
) )
}
</tbody>
</table>
</div>
)
}
}
ReactDOM.render( <div id="container"><App /></div>, document.querySelector( 'body' ) );
I was able to print harcoded, if I give value to the 'th' elements, but I want to print it dynamically, in case the data within the API has been changed.
You are welcome to contribute directly to my Repo: Fetching API data into a table
Here is how looks like my example, when columns values has been hardcoded within 'th' elements.
Any suggestions will be appreciated!
var data = {
columns: [
"Full name",
"Job title",
"Age",
"Bonus",
],
rows: [
[
"John Smith",
"team lead front-end",
30,
444.08,
],
[
"Tom Jones",
"front-end developer",
25,
333.3,
],
[
"Deborah Barnes",
"front-end developer",
21,
233.66,
],
[
"Isaac Roberson",
"technical support",
44,
353,
],
[
"Josh Brown",
"team lead back-end",
35,
353,
],
[
"Chester Mckinney",
"back-end developer",
33,
223.27,
],
[
"Ora Burton",
"back-end developer",
32,
192.92,
],
[
"Jim Brown",
"technical support",
19,
98.99,
],
],
}
class App extends React.Component
{
constructor()
{
super();
this.state = {
rows: [],
columns: []
}
}
componentDidMount()
{
this.setState( { rows: data.rows, columns: data.columns } );
}
render()
{
return (
<div id="container" className="container">
<h1>Final Table with React JS</h1>
<table className="table">
<thead>
<tr>
{this.state.columns.map(( column, index ) => {
return (<th>{column}</th>)
}
)
}
</tr>
</thead>
<tbody> {
this.state.rows.map(( row ) => (
<tr>
<td>{row[0]}</td>
<td>{row[1]}</td>
<td>{row[2]}</td>
<td>{row[3]}</td>
</tr>
) )
}
</tbody>
</table>
</div>
)
}
}
ReactDOM.render( <div id="container"><App /></div>, document.querySelector( 'body' ) );
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
Hope it may help
Not sure why you wanted to do columns[0], [1], [2] and [3]. Each column inside the map is a string. If you do columns[0] it will return you the first character from that which is what is happening in your case. Full Name, Job title, Age Bonus are rendered in your first image. First four characters in your columns.
The key attribute I added is just React's requirement to provide unique keys and has nothing to do with the problem.
this.state.columns.map((column, index) => (
<tr>
<th key={"columns-" + index.toString()}>
{column}
</th>
</tr>
))
I am building a dynamic table on my front end side, and at the end i need to know what was inserted on each cell of my table since it is editable, so i did this on my html:
<table class="table table-responsive">
<tbody>
<tr v-for="(row,idx1) in tableRows" :class="{headerRowDefault: checkHeader(idx1)}">
<td class="table-success" v-for="(col,idx2) in tableCols"><input v-model="items[idx1][idx2]" type="text" class="borderTbl" value="HEY"/></td>
</tr>
</tbody>
</table>
as you guys can see. i set inside the input a v-model with items[idx1][idx2] so i can pass the value to that line and columns, it is not working like this, i don't know how to set it.
This is my javascript:
export default {
name: 'app',
data () {
return {
table: {
rows: 1,
cols: 1,
key: 'Table',
tableStyle: 1,
caption: '',
colx: []
},
hasHeader: true,
hasCaption: true,
insert: 1,
idx2: 1,
items: []
}
},
computed: {
tableStyles () {
return this.$store.getters.getTableStyles
},
tableRows () {
return parseInt(this.table.rows)
},
tableCols () {
return parseInt(this.table.cols)
}
expected items array:
items:[
["john","Micheal"]
["john","Micheal"]
["john","Micheal"]
["john","Micheal"]
]
So, I think you're not pointing your models correctly.
Template:
<tr v-for="(row, idx1) in items">
<td class="table-success" v-for="(col, idx2) in row">
<input v-model="items[idx1][idx2]" type="text" />
</td>
</tr>
Script:
data () {
return {
items:[
["john","Micheal"],
["john","Micheal"],
["john","Micheal"],
["john","Micheal"]
];
};
}
Here's a working fiddle of it
I have some data that has the following format:
[name:'Name1', speed:'Val1', color:'Val2']
[name:'Name2', speed:'Val4', color:'Val5']
[name:'Name3', speed:'Val6', color:'Val7']
That I want to display in a table like this:
|Name1|Name2|Name3|
______|_____|______
speed |Val1 |Val4 |Val6
color |Val2 |Val5 |Val7
What I tried to do is group my data like this in the controller:
$scope.data = {
speeds: [{
...
},{
...
},{
...
}],
colors: [{
...
},{
...
},{
...
}],
};
But I am not sure what to put inside the empty areas, because all values there represent the values of the 'val1' variable for all Names (Accounts), and my tests until now keep failing.
You can imagine this as some sort of a comparisons matrix, that is used in order to see the all the values of the same variable across different accounts.
How can I represent the data in my model in order for me to successfully display them in a table as explained?
Edit
My difficulty lies in the fact that you create a table by going from row to row, so my html looks something like this:
<table md-data-table class="md-primary" md-progress="deferred">
<thead>
<tr>
<th ng-repeat="header in headers">
{{header.value}}
</th>
</tr>
</thead>
<tbody>
<tr md-auto-select ng-repeat="field in data">
<td ng-repeat="var in field">{{var.value}}</td>
</tr>
</tbody>
</table>
So as you can see I have a loop for each row, and a loop for each value of each row. This would be easier if I wanted to display the data horizontally, but I want the data vertically. So if we where talking about cars, we would have the car models as headers, and their respective characteristics(speed, color, etc) in each row.
If this is your basic structure:
var cols = [{name:'Name1', val1:'Val1', val2:'Val2'},
{name:'Name2', val1:'Val4', val2:'Val5'},
{name:'Name3', val1:'Val6', val2:'Val7'}];
This code
$scope.table = cols.reduce(function(rows, col) {
rows.headers.push({ value: col.name });
rows.data[0].push({ value: col.speed });
rows.data[1].push({ value: col.color });
return rows;
}, {headers:[], data:[[], []]});
will give you this structure for $scope.table:
$scope.table = {
headers : [{
value : "Name1"
}, {
value : "Name2"
}, {
value : "Name3"
}
],
data : [
[{
value : 'val1'
}, {
value : 'val4'
}, {
value : 'val6'
}
],
[{
value : 'val2'
}, {
value : 'val5'
}, {
value : 'val17'
}
]
]
};
<table md-data-table class="md-primary" md-progress="deferred">
<thead>
<tr>
<th ng-repeat="header in table.headers">
{{header.value}}
</th>
</tr>
</thead>
<tbody>
<tr md-auto-select ng-repeat="field in table.data">
<td ng-repeat="var in field">{{var.value}}</td>
</tr>
</tbody>
</table>
You could try this:
HTML
<table ng-app="myTable" ng-controller="myTableCtrl">
<thead>
<tr>
<th ng-repeat="car in cars">{{car.name}}</th>
</tr>
</thead>
<tbody>
<tr>
<td ng-repeat="car in cars">{{car.speed}}</td>
</tr>
<tr>
<td ng-repeat="car in cars">{{car.color}}</td>
</tr>
</tbody>
</table>
JS
angular.module("myTable",[])
.controller("myTableCtrl", function($scope) {
$scope.cars = [
{
name:'Name1',
speed:'Val1',
color:'Val2'
},
{
name:'Name2',
speed:'Val4',
color:'Val5'
},
{
name:'Name3',
speed:'Val6',
color:'Val7'
}
]
});
https://jsfiddle.net/ABr/ms91jezr/