How to render JSON data in reactjs? - reactjs

This is my people.js file.It contains data of two people.
var Data = [
{
"gender": "male",
"name": {
"title": "mr",
"first": "ruben",
"last": "dean"
},
"location": {
"street": "3070 york road",
"postcode": "LP0 5PG"
},
"email": "ruben.dean#example.com",
"login": {
"username": "crazydog764",
"password": "kane",
"sha256": "58841f853bffca51507549428aee2a6c14863c8219e5a4b563d58a5b97564c92"
},
"picture": {
"large": "https://randomuser.me/api/portraits/men/96.jpg",
"thumbnail": "https://randomuser.me/api/portraits/thumb/men/96.jpg"
},
"nat": "GB"
},
{
"gender": "male",
"name": {
"title": "mr",
"first": "daniel",
"last": "king"
},
"location": {
"street": "7618 taylor st",
"postcode": 35059
},
"email": "daniel.king#example.com",
"login": {
"username": "silvergorilla983",
"password": "1a2b3c4d",
"sha256": "df4eeb09df18d02d7fa49534a2cd6a03587d361f17aa7596d8ed7c025c5cb4d4"
},
"picture": {
"large": "https://randomuser.me/api/portraits/men/21.jpg",
"thumbnail": "https://randomuser.me/api/portraits/thumb/men/21.jpg"
},
"nat": "US"
}
]
module.exports = Data;
This is my PeopleList.jsx. Both files are in the same directory.
var React = require('react');
var Data = require('people');
var PeopleList = React.createClass({
render: function () {
return (
<div>
<ul>
</ul>
</div>
);
}
});
module.exports = PeopleList;
Can anyone tell me how to render both names (Ruben and Daniel) from the people.js file into the screen (within the unordered list)? Please provide code.
Thanks in advance.

This should do it:
<ul>
{Data.map(x => <li>{x.name.first}</li>)}
</ul>

You can do it using ES6 like this.
import {Data} from './path/to/people.json'
Then map over it.
Dara.map(person => console.log(person.name))

Related

How do I populate a graph from react-google-charts with data from a rest api?

I'm starting my studies in react and I'm not able to display the api data in the graph. The chart renders blank.
function ParticipationChart() {
const [chartData, setChartData] = useState([]);
useEffect(() => {
axios.get(`${BASE_URL}`)
.then((res) => {
setChartData(res.data.users);
console.log(res.data.users)
})
.catch((error) => {
console.log(error.response)
})
}, []);
return (
<div className="pieContainer">
<Chart
chartType="PieChart"
width="100%"
height="280px"
data={[
['users name', 'users participation'],
...chartData.map(users => [users.name, users.participation])
]}
options={options}
/>
</div>
)
}
The api returns the data like this:
{
"users": [
{
"id": "1674259593624",
"name": "Carlos",
"lastname": "Moura",
"participation": "5"
},
{
"id": "1674259666544",
"name": "Fernanda ",
"lastname": "Oliveira",
"participation": "15"
},
{
"id": "1674259711245",
"name": "Hugo",
"lastname": "Silva",
"participation": "20"
},
{
"id": "1674259994192",
"name": "Eliza",
"lastname": "Souza",
"participation": "20"
},
{
"id": "1674782074696",
"name": "Anderson",
"lastname": "Santos",
"participation": "40"
}
]
}
I tried a lot of things but i can't show the data. I can display local data normally, but external data is not working.

ReactJS - sort by ascending and descending

Im trying to reorder my results (JSON file) based on the title of my contacts.
The initial render is working fine, showing the results of the JSON file in the order they are in the JSON file.
When i change the select dropdown, i expect it to update the .map function (line 143) that is rendering out the results of the JSON.
What is happening is nothing. no change, no errors, just the select dropdown option changed to the selected value.
Not really sure why its not working, spent a few hours trying to debug, bet its something really simple I'm missing.
Any help would be greatly appreciated as I'm lost on what the problem is..
var getContactList = [
{
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"job": "Manager",
"email": "Sincere#april.biz",
"phone": "1-770-736-8031 x56442",
"website": "http://www.hildegard.org",
"company": "Romaguera-Crona"
},
{
"id": 2,
"name": "Ervin Howell",
"username": "Antonette",
"job": "CEO",
"email": "Shanna#melissa.tv",
"phone": "010-692-6593 x09125",
"website": "http://www.anastasia.net",
"company": "Deckow-Crist"
},
{
"id": 3,
"name": "Clementine Bauch",
"username": "Samantha",
"job": "Manager",
"email": "Nathan#yesenia.net",
"phone": "1-463-123-4447",
"website": "http://www.ramiro.info",
"company": "Romaguera-Jacobson"
},
{
"id": 4,
"name": "Patricia Lebsack",
"username": "Karianne",
"job": "Store Clerk",
"email": "Julianne.OConner#kory.org",
"phone": "493-170-9623 x156",
"website": "http://www.kale.biz",
"company": "Robel-Corkery"
},
{
"id": 5,
"name": "Chelsey Dietrich",
"username": "Kamren",
"job": "Store Clerk",
"email": "Lucio_Hettinger#annie.ca",
"phone": "(254)954-1289",
"website": "http://www.demarco.info",
"company": "Keebler LLC"
},
{
"id": 6,
"name": "Mrs. Dennis Schulist",
"username": "Leopoldo_Corkery",
"job": "Store Clerk",
"email": "Karley_Dach#jasper.info",
"phone": "1-477-935-8478 x6430",
"website": "http://www.ola.org",
"company": "Considine-Lockman"
},
{
"id": 7,
"name": "Kurtis Weissnat",
"username": "Elwyn.Skiles",
"job": "Manager",
"email": "Telly.Hoeger#billy.biz",
"phone": "210.067.6132",
"website": "http://www.elvis.io",
"company": "Johns Group"
},
{
"id": 8,
"name": "Nicholas Runolfsdottir V",
"username": "Maxime_Nienow",
"job": "Store Clerk",
"email": "Sherwood#rosamond.me",
"phone": "586.493.6943 x140",
"website": "http://www.jacynthe.com",
"company": "Abernathy Group"
},
{
"id": 9,
"name": "Glenna Reichert",
"username": "Delphine",
"job": "Store Clerk",
"email": "Chaim_McDermott#dana.io",
"phone": "(775)976-6794 x41206",
"website": "http://www.conrad.com",
"company": "Yost and Sons"
},
{
"id": 10,
"name": "Clementina DuBuque",
"username": "Moriah.Stanton",
"job": "Store Clerk",
"email": "Rey.Padberg#karina.biz",
"phone": "024-648-3804",
"website": "http://www.ambrose.net",
"company": "Hoeger LLC"
}
];
const App = React.createClass({
getInitialState: function() {
return {
orderSelect: ''
};
},
change: function(e) {
this.setState({
orderSelect: e.target.value
});
},
render: function() {
var contactsData = this.props.items,
orderSelect = this.state.orderSelect.trim().toLowerCase();
if (String(orderSelect) == "asc") {
contactsData.sort(function(a, b) {
return a.name.toLowerCase() > b.name.toLowerCase();
})
} else if (String(orderSelect) == "desc") {
contactsData.sort(function(a, b) {
return a.name.toLowerCase() < b.name.toLowerCase();
})
} else if (String(orderSelect) == "submitted") {
contactsData = getContactsList
}
return(
<div>
<select onChange={this.change} value={this.state.orderSelect}>
<option value="" disabled=""> Sort by </option>
<option value="submitted"> Submitted Date </option>
<option value="asc"> A - Z </option>
<option value="desc"> Z - A </option>
</select>
{
contactsData.map(function(l, index) {
return (
<div key={index}>
{l.name}
</div>
)
})
}
</div>
);
}
});
ReactDOM.render(
<App items={getContactList} />,
document.getElementById('app')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.21.1/babel.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react-dom.js"></script>
<div id="app"></div>
Did you get your answer on this? This is my solution, I hope it helps.
getContactList
.sort(
({ job: prevOr }, { job: curOr }) => prevOr - curOr
)
.map((slider) => (
<SliderItem key={slider.order} slider={slider} />
))
I would create then a ternary, if the value is A - Z the this one, if is Z - A then this code but with curOr - prevOr.

react/api - how to parse and map an array inside of api response

I'm trying to parse and map through the array "items" inside of this api response
[
{
"id": "",
"portal_account_id": "",
"platform": "",
"current_date": "2018-07-30T11:27:16+02:00",
"email": "",
"items": [
{
"itemId": "123",
"name": "vacuum 1",
"img": ""
},
{
"itemId": "456",
"name": "vacuum 2",
"img": ""
},
{
"itemId": "789",
"name": "vacuum 3",
"img": ""
}
]
}
]
this is what I have tried, it just parse through the response itself but I want to parse through the array inside of this response.
this.props.items.map((item) => {
return (
<Col className='' xs={12} md={4} key={item.id}>
<ProductItem handleOnAdd={this.dispachAddToCart.bind(this)} item={item} />
</Col>
);
})
Suppose this is your array;
const response = [
{
"id": "",
"portal_account_id": "",
"platform": "",
"current_date": "2018-07-30T11:27:16+02:00",
"email": "",
"items": [
{
"itemId": "123",
"name": "vacuum 1",
"img": ""
},
{
"itemId": "456",
"name": "vacuum 2",
"img": ""
},
{
"itemId": "789",
"name": "vacuum 3",
"img": ""
}
]
},
{
"id": "",
"portal_account_id": "",
"platform": "",
"current_date": "2018-07-30T11:27:16+02:00",
"email": "",
"items": [
{
"itemId": "123",
"name": "vacuum 1",
"img": ""
},
{
"itemId": "456",
"name": "vacuum 2",
"img": ""
},
{
"itemId": "789",
"name": "vacuum 3",
"img": ""
}
]
}
];
Then in render method do this.
render() {
return (
{response.map(item => {
return (
<div key={item.id}>
{item.items.map(product => {
return (
<div key={product.itemId}>
<p>{product.name}</p>
<p>path of image{product.img}</p>
</div>
);
})}
</div>
)
})}
);
}
The problem is you get an array of objects, and inside each object there is another array of objects.
You are probably getting JSON res from your API. You can destruct items from it and then iterate over it.
render(){
const { items } = this.props.response
items.map((item)=>{
return (
// do the stuff here
)
})
}
Do you mean you just want to parse the first item of the response array:
this.props.items[0].items.map

AngularJS multiple Scope needed for Autocomplete

I have an array structure like this.
[
{
"id": "1",
"name": "John",
"city": "NY"
},
{
"id": "2",
"name": "Gerold",
"city": "LA"
},
{
"id": "3",
"name": "Stuart",
"city": "Boston"
}
]
I need $scope like below for my autocomplete search.
$scope.name=["john","Gerold","Stuart"];
$scope.city=["NY","LA","Boston"];
can anyone help to get this using angularjs controller.
Thanks in Advance.!
Use MAP
$scope.users = [
{
"id": "1",
"name": "John",
"city": "NY"
},
{
"id": "2",
"name": "Gerold",
"city": "LA"
},
{
"id": "3",
"name": "Stuart",
"city": "Boston"
}
];
$scope.cities = $scope.users.map(function(obj){
return obj.city;
});
console.log($scope.cities);
You can also create a helper function that would do that for you and you don't have to define a map per function that you want, and you do it in just one run (hence just a bit faster)
Sample here ;)
var myArray = [
{
"id": "1",
"name": "John",
"city": "NY"
},
{
"id": "2",
"name": "Gerold",
"city": "LA"
},
{
"id": "3",
"name": "Stuart",
"city": "Boston"
}
]
function toScope(scopedPropertieNames, array) {
scopedPropertieNames.forEach(function(propertyName) {
if (! $scope[propertyName]) {
$scope[propertyName] = []
}
});
array.forEach(function (objecInArray) {
scopedPropertieNames.forEach(function(propertyName) {
$scope[propertyName].push(objecInArray[propertyName])
})
});
}
toScope(['name', 'city'], myArray);
console.log($scope) //{name: Array[3], city: Array[3]}
You can use MAP..
$scope.YourBigArray = [{
"id": "1",
"name": "John",
"city": "NY"
}, {
"id": "2",
"name": "Gerold",
"city": "LA"
}, {
"id": "3",
"name": "Stuart",
"city": "Boston"
}];
$scope.names = $scope.YourBigArray.map(function(object) {
return object.name;
});
$scope.cities = $scope.YourBigArray.map(function(object) {
return object.city;
});
You can do a filter to use unique things in array of names and cities..
function filterForDuplicate(things) {
return things.filter(function(item, pos) {
return things.indexOf(item) === pos;
});
}

How to read/repeat JSON data from AngularJS

I am pretty new to AngularJS so my apologies in that there are probably several concepts I am missing.
I'd like to take the following multi-level JSON string and parse/repeat the LastName elements.
Here is my attempt to do so with HTML / Javascript.
HTML
<!doctype html>
<html ng-app="nameApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0/angular.min.js"></script>
</head>
<body>
<div ng-controller="jsonGrab">
<hr>
<h1># of Records {{output}}</h1>
<ul>
<li data-ng-repeat="attribute in output.attributess"> {{attributes.LastName}}</li>
</ul>
</div>
</body>
</html>
Javascript
var nameApp = angular.module('nameApp',[]);
nameApp.controller('jsonGrab', function ($scope) {
// Comment
$scope.output = '[{
"attributes": {
"type": "Contact",
"url": "/services/data/v32.0/sobjects/Contact/003o000000BTRXuAAP"
},
"Email": "rose#edge.com",
"FirstName": "Rose",
"Id": "003o000000BTRXuAAP",
"LastName": "Gonzalez"
}, {
"attributes": {
"type": "Contact",
"url": "/services/data/v32.0/sobjects/Contact/003o000000BTRXvAAP"
},
"Email": "sean#edge.com",
"FirstName": "Sean",
"Id": "003o000000BTRXvAAP",
"LastName": "Forbes"
}, {
"attributes": {
"type": "Contact",
"url": "/services/data/v32.0/sobjects/Contact/003o000000BTRXwAAP"
},
"Email": "jrogers#burlington.com",
"FirstName": "Jack",
"Id": "003o000000BTRXwAAP",
"LastName": "Rogers"
}, {
"attributes": {
"type": "Contact",
"url": "/services/data/v32.0/sobjects/Contact/003o000000BTRXxAAP"
},
"Email": "pat#pyramid.net",
"FirstName": "Pat",
"Id": "003o000000BTRXxAAP",
"LastName": "Stumuller"
}, {
"attributes": {
"type": "Contact",
"url": "/services/data/v32.0/sobjects/Contact/003o000000BTRXyAAP"
},
"Email": "a_young#dickenson.com",
"FirstName": "Andy",
"Id": "003o000000BTRXyAAP",
"LastName": "Young"
}, {
"attributes": {
"type": "Contact",
"url": "/services/data/v32.0/sobjects/Contact/003o000000BTRXzAAP"
},
"Email": "barr_tim#grandhotels.com",
"FirstName": "Tim",
"Id": "003o000000BTRXzAAP",
"LastName": "Barr"
}, {
"attributes": {
"type": "Contact",
"url": "/services/data/v32.0/sobjects/Contact/003o000000BTRY0AAP"
},
"Email": "bond_john#grandhotels.com",
"FirstName": "John",
"Id": "003o000000BTRY0AAP",
"LastName": "Bond"
}, {
"attributes": {
"type": "Contact",
"url": "/services/data/v32.0/sobjects/Contact/003o000000BTRY1AAP"
},
"Email": "spavlova#uog.com",
"FirstName": "Stella",
"Id": "003o000000BTRY1AAP",
"LastName": "Pavlova"
}, {
"attributes": {
"type": "Contact",
"url": "/services/data/v32.0/sobjects/Contact/003o000000BTRY2AAP"
},
"Email": "lboyle#uog.com",
"FirstName": "Lauren",
"Id": "003o000000BTRY2AAP",
"LastName": "Boyle"
}, {
"attributes": {
"type": "Contact",
"url": "/services/data/v32.0/sobjects/Contact/003o000000BTRY3AAP"
},
"Email": "b.levy#expressl&t.net",
"FirstName": "Babara",
"Id": "003o000000BTRY3AAP",
"LastName": "Levy"
}]';
Result: # of Records 1937
Shows the number of characters (I think) instead of the number of records returned and the unordered list is not displaying.
Look at the code:
$scope.output = '[{ ... }]';
So, output is a variable of type string. It's not an array. If you want an array, it should be
$scope.output = [{ ... }];
But then, the code would still be wrong:
<li data-ng-repeat="attribute in output.attributess">
{{attributes.LastName}}
</li>
output is an array. It doesn't have any attributess field. So it should be
<li data-ng-repeat="element in output">
{{ element.attributes.LastName }}
</li>

Resources