Cannot render child object in React JS table - javascript

I am trying to render an object held in state. The contents of this.state is:
"statement": {
"creator": "8ff243b2-f21e-43f3-9090-4aa679fbeb1a",
"id": "bf4c965e-bd59-48c8-b31a-8f67529e5fde",
"impactors": [
"978388e8-2987-4c89-82b6-4da619d82935",
"1d75e2a7-bf2a-4f55-ba68-373752b24f98"
],
"score": {
"impactors": 2,
"net": 3,
"percentage": 0.75,
"total_votes": 4
},
"statement": "The Earth is round."
}
In my React JS app, I am able to render some of the child object (statement) but not all. Here is my code:
renderStatement() {
return (
<tbody>
<tr>
<td>Statement: </td>
<td>{this.state.statement.score}</td>
</tr>
</tbody>
)
}
As expected, the above code returns an error: Error: Objects are not valid as a React child (found: object with keys {impactors, net, percentage, total_votes}). If you meant to render a collection of children, use an array instead.
What I actually want is percentage, which is a node underneath score. When I try to drill down and have it just render percentage, like this:
renderStatement() {
return (
<tbody>
<tr>
<td>Statement: </td>
<td>{this.state.statement.score.percentage}</td>
</tr>
</tbody>
)
}
I get the following error: TypeError: Cannot read property 'percentage' of undefined.
Any of the other objects ('creator', 'id', 'impactors', 'statement') work just fine.

This is how I fixed it:
renderStatement() {
const score = this.state.statement.score || {}
return (
<tbody>
<tr>
<td>Statement: </td>
<td>{score.percentage}</td>
</tr>
</tbody>
)
}

you can do the following:
renderStatement() {
const text = (typeof this.state.statement.score !== "undifined") ?
this.state.statement.score.percentage : ''
return (
<tbody>
<tr>
<td>Statement: </td>
<td>{text}</td>
</tr>
</tbody>
)
}

Related

How can ı add my values to table in react

I am trying to make form project. When person submmit to personal info to form. I want add this info to Table. But I get this error when I am adding info to table.
Uncaught Error: Objects are not valid as a React child (found: object with keys {inputValue}). If you meant to render a collection of children, use an array instead.
I know this is related to const newToTable part. But I don't know how to make it right. Please help me, ıf you know how can ı solve this problem.
This is my contact.js
const buttonOnClick = () => {
if (inputValue === "" || emailValue === "" || phoneNumberValue === "") {
setShowModal(false);
} else {
setShowModal(true);
// setInputValue("");
//setEmailValue("");
//setPhoneValue("");
// sa
}
const newToTable = [...addFormData, { fullName:{inputValue},email:{emailValue}, phoneNumber:{phoneNumberValue},country:{countryValue} }];
setAddFormData(newToTable);
console.log(`Form submitted, ${showModal}`);
}
This is my AddTable.js
<div className="app-container">
<form>
<Table>
<thead>
<tr>
<th>Full Name</th>
<th>Email </th>
<th>Phone Number</th>
<th>Country</th>
</tr>
</thead>
<tbody>
{addFormData.map((addForm) => (
<tr>
<td>{addForm.fullName}</td>
<td>{addForm.email}</td>
<td>{addForm.phoneNumber}</td>
<td>{addForm.counry}</td>
</tr>
))}
</tbody>
</Table>
</form>
</div>
You've accidently wrapped your form values in objects here:
const newToTable = [...addFormData, { fullName:{inputValue},email:{emailValue}, phoneNumber:{phoneNumberValue},country:{countryValue} }];
For example fullName:{inputValue} will evalute to fullName: { inputValue: 'the value' }
Instead you need:
const newToTable = [
...addFormData,
{
fullName: inputValue,
email: emailValue,
phoneNumber: phoneNumberValue,
country: countryValue,
},
];
This is what the error means by Objects are not valid as a React child - when it tries to render your table, the values being passed are objects such as { inputValue: 'the value' } (this is the (found: object with keys {inputValue}) part of the error - an object with inputValue as a key).

Iterating over object and displaying as table - React.js

I have an object:
{
cities: {
MCR: "Manchester",
LDN: "London",
NYC: "New York"
}
}
and I want to iterate over these and display them in a table format which will show the city code and the long name next to it. Something like:
<tbody>
<tr>
<th>City Code</th>
<th>City Name</th>
</tr>
<tr>
{Object.entries(cities).map(([key, value]) => {
<>
<td>{key}</td>
<td>{value}</td>
</>
}
)}
</tr>
</tbody>
However this doesn't display anything and also shows an error when hovering over value:
Type 'unknown' is not assignable to type 'ReactNode'.ts(2322)
I'm quite new to React and wondering how best to display this information?
Thanks
let say you have an object as:
const obj = {
cities: {
MCR: "Manchester",
LDN: "London",
NYC: "New York"
}
};
It would be better to loop over cities and create a new tr so that It looks like a table
CODESANDBOX LINK
You want to map over the cities then you should return it from map as:
<tbody>
<tr>
<th>City Code</th>
<th>City Name</th>
</tr>
{ Object.entries( obj.cities ).map( ( [key, value] ) => {
return ( // PROBLEM SHOULD RETURN
<tr>
<td>{ key }</td>
<td>{ value }</td>
</tr>
);
}
) }
</tbody>
You need to return the result in each iteration. Also, each iteration would return a tr with a key prop:
{
Object.entries(obj.cities).map(([key, value]) => (
<tr key={key}>
<td>{key}</td>
<td>{value}</td>
</tr>
))
}
Note: since city is a key in an object, you'll need to access it as above
You are just missing the return in your map's callback function. Always remember to include a return in your arrow functions when using it like this: () => {}. It is easy to miss because ()=>() would return whatever you write in the second () but in the former example this is not true.

How to render my multidimensional array of objects in react

I am trying to render my array of objects inside my table but it shows "Cannot read property 'monthlytarget' of undefined", I am using axios to fetch the result and render inside the table
Axios :
http.get(apiReportsEndpoint+"?empid="+this.props.match.params.id)
.then(response =>{
this.setState({
report:response.data.data.monthlytarget
})
});
Response I receive from API
"data":{
"monthlytarget":[
{
"quarter":1,
"period_start":"2019-04-01",
"monthlytarget":{
"04":{
"targetpm":"213120",
"invoice_values":[
],
"revenuepm":0,
"targetpercentage":0,
"joinees":0
},
"05":{
"targetpm":"213120",
"invoice_values":[
],
"revenuepm":0,
"targetpercentage":0,
"joinees":0
}
}
},
{ quarter":2 ...},
{ quarter":3 ...},
]
}
I want to render values inside "monthlytarget" as rows inside table
<thead>
<tr>
<th>MONTH</th>
<th>TARGET PER MONTH</th>
<th>REVENUE PER MONTH</th>
</tr>
</thead>
<tbody>
{
this.state.report.map((revenuereport) =>{
{Object.keys.map.monthlytarget(premise,index) => (
<tr>
<td>{index}</td>
<td>{premise.targetpm}</td>
<td>{premise.revenuepm}</td>
</tr>
))}
})
}
</tbody>
To create one table out of all the data you could do the following:
this.state.report
.map(({ monthlytarget }) => Object.entries(monthlytarget))
.flat()
.map(([key,value], index) => (
<tr key={index}>
<td>{index}</td>
<td>{value.targetpm}</td>
<td>{value.revenuepm}</td>
</tr>
));
what do you mean by calling Object.keys.map.monthlytarget? if you are trying to loop the array and get JSX, do this:
this.state.report.map((revenuereport) =>
Object.keys(revenuereport.monthlytarget).map((premise, index) => (
<tr>
<td>{index}</td>
<td>{revenuereport.monthlytarget[premise].targetpm}</td>
<td>{revenuereport.monthlytarget[premise].revenuepm}</td>
</tr>
))
);
Do pay attention to indents and brackets, code snippet in the question seems not gonna work at all.
It should be...
this.state.report.map(({ monthlytarget }, i) =>
Object.values(monthlytarget).map({ targetpm, revenuepm }, i) =>
<tr>
<td>{i}</td>
<td>{targetpm}</td>
<td>{revenuepm}</td>
</tr>
))

Issue with Aurelia class.bind with checked.bind

I am trying to use class.bind in a way that makes it dependent on checked.bind.
My use case is pretty simple. I have a list of items, displayed using a table. Each row of this table has a checkbox. I want to mark a row as "selected" whenever the corresponding checkbox (of the row) is checked.
For this I have used following binding:
<table class="table table-striped table-hover table-responsive">
<tbody>
<tr repeat.for="item of items" class.bind="$parent.selectedItems.indexOf(item)>-1?'info':''">
<td>
<input type="checkbox" checked.bind="$parent.selectedItems" model.bind="item" />
</td>
<td>${item.id}</td>
<td>${item.name}</td>
</tr>
</tbody>
</table>
However, the same doesn't work as intended, and this can be seen in this plunk.
As a workaround I used a getter with #computedFrom('selectedItems', 'items') and/or declarePropertyDependencies(App, 'classes', ['selectedItems', 'items']); , as follows:
import {computedFrom, declarePropertyDependencies} from "aurelia-framework";
export class App {
...
#computedFrom('selectedItems', 'items')
get classes() {
const self = this;
const retval= self.items.map((item: any) => {
return self.selectedItems.indexOf(item) > -1 ? "info" : "";
});
return retval;
}
}
//declarePropertyDependencies(App, 'classes', ['selectedItems', 'items']);
However, this too does not work as can be seen here in this workaround plunk.
It only works, if none of #computedFrom and/or declarePropertyDependencies is used, and that obviously involves dirty-checking.
Is there a clean way to do this?
The binding system will reevaluate the class binding expression class.bind="$parent.selectedItems.indexOf(item)>-1?'info':''" anytime a property used in the expression changes. The selectedItems property never changes, it remains the same array instance. Understandably this is a little confusing because the array instance is mutating. Here's a workaround you can use: add selectedItems.length to the binding expression... we know it will change when items are pushed/popped from the array.
Here's an example: https://gist.run?id=09d32941842352ff0025
app.html
<template>
<p>${message}</p>
<table class="table table-striped table-hover table-responsive">
<tbody>
<tr repeat.for="item of items" class.bind="selectedItems.length === 0 || selectedItems.indexOf(item) === -1 ? '' : 'info'">
<td>
<input type="checkbox" checked.bind="selectedItems" model.bind="item" />
</td>
<td>${item.id}</td>
<td>${item.name}</td>
</tr>
</tbody>
</table>
${selectedItems.length} items selected
</template>
app.js
export class App {
constructor(router) {
this.message = "Hello World!";
this.items = [{
id: 1,
name: "A"
}, {
id: 2,
name: "B"
}, {
id: 3,
name: "C"
}];
this.selectedItems=[];
}
}

Iterating through a JSON response in JSX Render for React.js

I'm trying to create a table from a JSON response formulated from a submitted form, therefore the initial render needs to be blank, but this blank state is proving to be an issue.
The issue is complicated further by the fact that the response could have different headers, number of columns, and order.
Parent component
This gets the resultData and passes it to a child component
<ReportsTable title={this.props.title} resultData={this.state.resultData} />
Child component
var ReportsTable = React.createClass({
render: function() {
var resultData = this.props.resultData;
return(
<div>
<h3>{this.props.title}</h3>
<table>
<tr>
//iteration here
</tr>
</table>
</div>
)
}
});
Any attempt at iteration gives me a
Uncaught TypeError: Cannot read property XXX of undefined
The Data received is in this type of format
[Array[1], Array[1]]
0: Array[1]
0: Object
family_name: "Sales"
gross_margin: "0%"
net_profit: "$0.00"
profit_percent: "0%"
quantity_on_hand: 2863
retail: "$9,347.12"
total_cost: "$7,615.96"
total_sold: 49
1: Array[1]
0: Object
family_name: "Service"
gross_margin: "0%"
net_profit: "$0.00"
profit_percent: "0%"
quantity_on_hand: 147.5
retail: "$939.05"
total_cost: "$268.40"
total_sold: 10.8
[UPDATE]
So we modified the response from the server so that I get one less nest in the Array. But now when I try
resultData.map(function(item) { })
and I get an "Uncaught TypeError: undefined is not a function" error as I'm trying to map through the properties of the Object. When I try to map through an Array it works so I don't think it's my syntax.
In the end, my trouble is iterating through the properties of each Object.
This part from the parent works
{resultData.map(function(tableRow, i) {
return (
<TableRow tableRow={tableRow} key={i} />
);
})}
This part in the Child Component does not
var TableRow = React.createClass({
render: function(){
var tableRow = this.props.tableRow;
console.log(tableRow);
return(
<tr key={tableRow}>
{tableRow.map(function(tableItem, i){
<td key={i}>{tableItem}</td>
})}
</tr>
);
}
});
I have had the same problem.
The reason why i got "Uncaught TypeError: undefined is not a function" was because i tried to iterate over the properties of a json object using map which is not possible. The solution for me was to iterate over the keys of the json object using Object.keys(). See below for my solution.
Data:
{
"status": {
"build": {
"a":"b",
"c":"d"
}
}
}
`render: function(){
var buildInfo = this.props.applicationInfo.status.build;
var properties = Object.keys(buildInfo).map((k, idx) => {
return (
<p key={idx}><strong>{k}</strong> - {buildInfo[k]}</p>
);
});
return(
<div>
{properties}
</div>
);
}`
If you have JSON instead of Array and you want to loop in JSX react render function use Object.keys:
<select className="form-control" >
{Object.keys(item.unit).map(unit => {
return <option value="1">1</option>
})}
</select>
So this works
<table className="table table-condensed table-striped">
<thead>
<tr>
{resultTitles.map(function(title){
var textAlignLeft = false;
if(textLeftMatch.test(title)){
textAlignLeft = true;
}
title = title.replace(/_/g, " ");
return <th key={title} className={textAlignLeft ? 'text-left' : ''}>{title}</th>
})}
</tr>
</thead>
<tbody>
{resultData.map(function(tableRow, i) {
return (
<TableRow tableRow={tableRow} key={i} />
);
})}
</tbody>
</table>
var TableRow = React.createClass({
render: function(){
var tableRow = this.props.tableRow;
var rowArray = $.map(tableRow, function(value, index){
return [value];
});
return(
<tr key={tableRow}>
{rowArray.map(function(tableItem, i){
return <td key={i} className={(i === 0) ? 'text-left' : ''}>{tableItem}</td>
})}
</tr>
);
}
});
However, after searching for awhile, I found a better starting point found here http://dynamictyped.github.io/Griddle/quickstart.html

Categories