how to assign comment count to post using reactjs - reactjs

The code below works fine and display post record successfully.
No I want to get the comment count for each post based on post (pid).
I have implemented this function below
getCounterByPid(pid)
My issue: The function above display comment counting 3 for each post.
Normally, the post with pid 102 should show 2 comment count, then others 1 count each
here is the code
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script src="build/react.min.js"></script>
<script src="build/react-dom.min.js"></script>
<script src="build/browser.min.js"></script>
<script src="build/jquery.min.js"></script>
<div id="app"></div>
<script type="text/babel">
class Application extends React.Component {
//function Application() {
constructor(props) {
super(props);
this.state = {
post: {"results":
[
{"desc": "my first product", "pid": "101"},
{"desc": "my second product", "pid": "102"},
{"desc": "my 3rd product", "pid": "103"},
]},
comment: {"res":
[
{"comment": "hello 1", "pid": "101"},
{"comment": "hello 2", "pid": "102"},
{"comment": "hello 3", "pid": "103"},
{"comment": "hello 4", "pid": "102"},
]},
};
}
// get total comment count for each post
getCounterByPid(pid) {
const resIndex = this.state.comment.res.findIndex(el => pid === el.pid);
//const c1 = this.state.comment.res[resIndex].counting;
const comment_count = this.state.comment.res[resIndex].pid;
const comment_l = comment_count.length;
//alert(comment_count.length);
return comment_l;
};
render() {
return (
<div>
<div>
<ul>
{this.state.post.results.map((obj, i) => (
<li key={i}>
{obj.pid} - {obj.desc}<br />
<span> Comment count: ({this.getCounterByPid(obj.pid)})</span>
</li>
))}
</ul>
</div>
</div>
);
}
}
ReactDOM.render(<Application />, document.getElementById('app'));
</script>
<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>
</body>
</html>

With your current code:
const resIndex = this.state.comment.res.findIndex(el => pid === el.pid);
//const c1 = this.state.comment.res[resIndex].counting;
const comment_count = this.state.comment.res[resIndex].pid;
const comment_l = comment_count.length;
findIndex will find one of the comments in your array, it doesn't matter which it returns but it will return an index.
comment_count however will be the actual pid of that comment so 101, 102 or 103 depending on the value of findIndex
Finally, you are returning the length of that pid, which will always be 3.
Rather than do that, you can just filter the comments to find all the comments which are related to that specific pid. Then return the length of that filtered array.
getCounterByPid(pid) {
const comments = this.state.comment.res.filter(el => pid === el.pid);
return comments.length;
}
I have created a working example here: https://codesandbox.io/s/frosty-sunset-szn6t

Related

Display a json array of object in ReactJS

I have an array of object and want display in a single line in ReactJS. The object look like:
[
{
name:"jane",
age : "20"
},
{
name:"mary",
age : "21"
}
{
name:"john",
age : "19"
}
]
I want display the result to be :
jane 20, mary 21, john 19
e.g
<span className="name>data.name</span> <span className="age>data.age</span>
I have a function but that concat the value but not sure now to get my desire output
const getData = () => {
var val = ''
roles.map((data, inx) => {
val = val + data.name + data.age
})
return (
<span>{val}</span>
)
}
how can I do this
Concatenating like
val = val + data.name + data.age
won't work, because you want JSX elements (spans), not plain strings.
When mapping, check the index. If the index is 1 or more, add a comma before the first span when creating the JSX.
const arr = [
{
name:"jane",
age : "20"
},
{
name:"mary",
age : "21"
},
{
name:"john",
age : "19"
}
]
const App = () => {
return arr.map(({ name, age }, i) => (
<React.Fragment>
{i === 0 ? null : ','}
<span className="name">{name}</span> <span className="age">{age}</span>
</React.Fragment>
));
};
ReactDOM.render(<App />, document.querySelector('.react'));
<script crossorigin src="https://unpkg.com/react#16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom#16/umd/react-dom.development.js"></script>
<div class='react'></div>

how to dynamically parse Json data using reactjs

I have a requirement to determine a generic standard approach to read the JSON data ( should be able to read any JSON structure) and display in reactjs page.
I know that if we know JSON structure, we can traverse through it and display the data in the page accordingly. But here JSON structure
should be dynamically determined via code and we should not code specifically for each JSON structure.
For example, I have given Sample1.json and Sample2.json files below. My program should be able to parse Sample1.json if I use it and display
them on the page. If I use Sample2.json, still it should be able to parse them and display the data dynamically. We should not have
code specifically like archive_header.tracking_id or stock_ledger_sales_key.version_number...etc.
Can someone please let me know how to handle this scenario?
Sample1.json
{
"archive_header": {
"tracking_id": "914553536-FRM01-20163609140455-000000001",
"archived_timestamp": "2018-05-08T09:14:04.055-05:00"
},
"journal_record_key": {
"location_number": "389234",
"dept_number": "28822"
},
"journal_record_detail": {
"financial_from_item_number": "771",
"financial_to_item_number": "771"
}
}
Sample2.json
{
"stock_ledger_sales_key": {
"version_number": "12",
"account_month_number": "01",
"account_year_number": "2016"
},
"stock_ledger_sales_detail": {
"mature_increase_mtd_percentage": "1.2",
"mature_increase_stdt_percentage": "2.3",
"mature_increase_ytd_percentage": "2"
}
}
You can just iterate over the keys recursively:
function recursively_iterate(object, parent_name="") {
output = ""
for (key in Object.keys(object)) {
if (typeof object[key] == "object") {
output = output + recursively_iterate(object[key], key)
}
output = output + parent_name + "." + key + ": " + object[key] + "\n"
}
return output
}
To display the information as you said, we can do something like this:
const jsonDOM = json => {
return Object.keys(json).map(key => {
return Object.keys(json[key]).map(child => {
return (<div>
<p>{child}</p>
<p>{json[key][child]}</p>
</div>
);
});
});
};
return (<div>
<h2>JSON 1</h2>
{jsonDOM(json1)}
<h2>JSON 2</h2>
{jsonDOM(json2)}
</div>
);
Here is the live demo
Hope it helps :)
You can use JSON.stringify and <pre> tag to output any json you like.
const sample1 = {
archive_header: {
tracking_id: "914553536-FRM01-20163609140455-000000001",
archived_timestamp: "2018-05-08T09:14:04.055-05:00"
},
journal_record_key: {
location_number: "389234",
dept_number: "28822"
},
journal_record_detail: {
financial_from_item_number: "771",
financial_to_item_number: "771"
}
};
const sample2 = {
stock_ledger_sales_key: {
version_number: "12",
account_month_number: "01",
account_year_number: "2016"
},
stock_ledger_sales_detail: {
mature_increase_mtd_percentage: "1.2",
mature_increase_stdt_percentage: "2.3",
mature_increase_ytd_percentage: "2"
}
};
class App extends React.Component {
render() {
return (
<div>
<h3>sample1</h3>
<pre>
<code>{JSON.stringify(sample1, null, 2)}</code>
</pre>
<h3>sample2</h3>
<pre>
<code>{JSON.stringify(sample2, null, 2)}</code>
</pre>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>

How sum column values and format cell using conditional formatting?

I started to develop in React.js, and I'm using React-Bootstrap-Table.
I need to get the sum of the total of a particular column (updates on every change in search field).
I also want to add custom CSS for conditional formatting based on value (example, if amount is less than average, need to be green
text if amount is near average yellow, if amount is above
average but less than maximum orange else red).
Also number field needs to be right aligned
Code can be viewed here
var DataTable = ReactDataComponents.DataTable;
// Generate random data
var names = ['201801003', '201801002', '201801004', '201801005', '201801006'];
var cities = ['2018', '2017', '2017', '2017', '2017', '2017'];
var addresses = ['Travancore', 'Sivagangai', 'Pudhukottai', 'Madurai'];
var states = ['1200', '350', '6400', '1700', '750'];
var data = [];
for (var i = 0; i < 1000; i++) {
data.push({
id: i,
name: names[~~(Math.random() * names.length)],
city: cities[~~(Math.random() * cities.length)],
address: addresses[~~(Math.random() * addresses.length)],
state: states[~~(Math.random() * states.length)]
});
}
var columns = [{
title: 'CID',
prop: 'name'
}, {
title: 'Area',
prop: 'city'
}, {
title: 'Authority',
prop: 'address'
}, {
title: 'Amount',
prop: 'state'
}];
ReactDOM.render(React.createElement(DataTable, {
className: 'container',
keys: 'id',
columns: columns,
initialData: data,
initialPageLength: 5,
initialSortBy: {
prop: 'city',
order: 'descending'
},
pageLengthOptions: [5, 20, 50]
}), document.getElementById("root"));
<title>React Table</title>
<link rel='stylesheet prefetch' href='https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha/css/bootstrap.min.css'>
<link rel='stylesheet prefetch' href='https://cdn.rawgit.com/carlosrocha/react-data-components/v1.0.0/css/table-twbs.css'>
<link rel='stylesheet prefetch' href='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.2.0/css/font-awesome.min.css'>
<body>
<br>
<h3> Area</H3>
<br>
<div id="root"></div><br>
<h3> Sum</H3>
<br>
<div id="root"></div>
<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>
<script src="https://npmcdn.com/react-data-components#1.0.1/dist/react-data-components.min.js"></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha/css/bootstrap.min.css'></script>
</body>
Thank you
For every row you make, add it to a counter in your state
Do conditional css based on the value in the counter
Align it to the right with css

Cannot recieve the values from JSON-string by angular.js

I have tried to implement some methods from a tutorial javasampleapproach.com/spring-framework/spring-boot/spring-jpa-postgresql-angularjs-example-spring-boot but it doesn't work for me.
When I hit the GET ALL CUSTOMERS-button nothing comes up. When I tried to add a testmessage with the json-text that I have requested from the RestController and just use #scope.allPersons.data the complete json-text come up but if I try to get the valuesin the json-responese it is either undefined or nothing comes up.
First of all, the RestController. I have tried with #RequestMapping(value="/findallresponse", produces = "application/json")and the default from the tutorial as showed in the code. The reason for making my own String Json is that if I responded with the Iteratable-object the response get recursive because of #ManyToMany-relation. And when I troubleshoot I left out the Hobbypart because that was the ManyToMany-relationship value.
#RequestMapping("/findallresponse")
public Response findAllResponse(){
ArrayList firstNameStr=new ArrayList<String>();
ArrayList lastNameStr=new ArrayList<String>();
ArrayList hobbyStr=new ArrayList<String>();
ArrayList idStr=new ArrayList<String>();
boolean startLoop=true;
String jsonPersonBeggining="{\"persons\":[";
String jsonPersonEnd="]}";
String jsonPerson="";
for(Person person : personService.findAll()){
if(startLoop==true)
{
startLoop=false;
}
else
{
jsonPerson+=",";
}
jsonPerson+="{";
jsonPerson+="\"firstName\":\""+person.getFirstName()+"\",";
jsonPerson+="\"lastName\":\""+person.getLastName()+"\",";
//jsonPerson+="\"hobby\":\""+person.getHobby()+"\",";
jsonPerson+="\"id\":\""+person.getId()+"\"";
jsonPerson+="}";
}
jsonPerson=jsonPersonBeggining+jsonPerson+jsonPersonEnd;
return new Response("Done",jsonPerson);
}
Here is the Response-class just as in the tutorial
public class Response {
private String status;
private Object data;
public Response() {
}
public Response(String status, String data) {
this.status = status;
this.data = data;
}
public String getStatus() {
return status;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public void setStatus(String status) {
this.status = status;
}
}
The javascript-file as in the tutorial. The #getResultMessage is to test that the json-string is recieved at all. And it is. But after that I can't access the post in it, for instance
firstName or
lastName
var app = angular.module('app', []);
app.controller('getallpersonsController', function($scope, $http, $location)
{
$scope.showAllPersons = false;
$scope.getAllPersons = function() {
var url = $location.absUrl() + "findallresponse";
var config = {
headers : {
'Content-Type' : 'application/json;charset=utf-8;'
}
}
$http.get(url, config).then(function(response) {
if (response.data.status == "Done") {
$scope.allpersons = response.data;
$scope.showAllPersons = true;
$scope.getResultMessage = $scope.allpersons.data;
} else {
$scope.getResultMessage = "get All Customers Data Error!";
}
}, function(response) {
$scope.getResultMessage = "Fail!";
});
}
});
This is the output on this is the #getResultMessage taken from #scope.allpersons.data
{"persons":[{"firstName":"Adam","lastName":"Johnson","id":"87"},{"firstName":"Anna","lastName":"Persson","id":"90"},{"firstName":"Nils","lastName":"Svensson","id":"93"}]}
And the jsp-file
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Spring Boot Example</title>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<meta name="viewport" content="width=device-width, initial-scale=1" />
<script
src="http://ajax.googleapis.com/ajax/libs/angularjs/1.6.0/angular.min.js">
</script>
<script src="/js/angular.js"></script>
<link rel="stylesheet"
href="http://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css"
/>
</head>
<body>
<div class="container" ng-app="app">
<h1>AngularJS - Spring JPA - PostgreSQL</h1>
<div class="row">
<div ng-controller="getallpersonsController" class="col-md-3">
<h3>All Customers</h3>
<button ng-click="getAllPersons()">
Get All Customers
</button>
<div ng-show="showAllPersons">
<ul class="list-group">
<li ng-repeat="persons in allpersons.data">
<h4 class="list-group-item">
<strong>Customer {{$index}}</strong><br />
Id: {{persons.id}}<br />
First Name: {{persons.firstName}}<br />
Last Name: {{persons.lastName}}
</h4>
</li>
</ul>
</div>
<p>{{getResultMessage}}</p>
</div>
</div>
</div>
</body>
</html>
UPDATE!!
Here is some calls on the response if that can give any clue?
data=[object Object] status=200
statustext=undefined
headers=function (d){b||(b=od(a));return d?(d=b[L(d)],void 0===d&&(d=null),d):b} config=[object Object]
Can anyone see if I missed something? In the jsp-file the ng-repeatloop is not working, it doesn't seems to be able to get the value from the json? Thanks

Convert json Array to Object on Vue Js 2

I'm trying to convert my data json from an array to an object to be able to consume the data but something went wrong...
Here is the data json sample:
[
{
"id": 1,
"title": "my title",
"imgHero": "../../path/hero.jpg"
}
]
And here is the Vue component:
<template>
<div class="hero">
<img :src="blog.imgHero" alt="hero image" class="heroImg">
<h3 class="heroTitle">{{ blog.title }}</h3>
</div>
</template>
<script>
import tripsJson from '#/data/trips.json'
export default {
name: 'App',
data () {
return {
array: tripsJson,
blog: {}
}
},
created () {
var obj = this.array.reduce(function (acc, cur, i) {
acc[i] = cur
return acc
}, {})
this.blog = obj
console.log(this.blog)
}
}
</script>
Any help or suggestion is more than welcome. Thx

Resources