show images on screen by using urls - javascript

I have urls of images from flicker and I want to show them on screen but I can't get any images.
Here is my code:
loadimages(e) {
e.preventDefault();
this.setState({spinner:true});
console.log('spinner');
// axios.get(`https://www.pexels.com/`).then(res=>{
// console.log(this.state.spinner);
// this.setState({images:res.data,spinner:false});
// });
axios.get( "https://api.flickr.com/services/feeds/photos_public.gne?tags=kitten&format=json&nojsoncallback=true" )
.then((response) => {
console.log('hellodata', response.data.items);
this.setState({
images: response.data.items,
spinner:false
});
console.log('images', this.state.images);
})
.catch(function(err){
console.log(err);
})
}
render() {
const mappedStorage = this.state.images.map((item) => <li>{item.media.m}</li>)
return (
<div className="fun2">
{this.state.spinner ?
<div>
<MDSpinner size={50}/>
</div>
: null
}
{/* <ul>{mappedStorage} */}
<ul>
<img src={mappedStorage} />
</ul>
<button onClick={this.loadimages}>
Click Here
</button>
</div>
)
}
This is a sample response from the API:
{
"title": "Recent Uploads tagged kitten",
"link": "https://www.flickr.com/photos/tags/kitten/",
"description": "",
"modified": "2018-11-13T13:31:05Z",
"generator": "https://www.flickr.com",
"items": [
{
"title": "flo_02-10-06 001",
"link": "https://...",
"media": {
"m": "https://....jpg"
},
"date_taken": "2018-11-13T12:09:32-08:00",
"description": "......"
"published": "2018-11-13T11:11:06Z",
"author": "nobody#flickr.com (\"nikita zenon2\")",
"author_id": "125437611#N07",
"tags": "some tags here"
},
{
"title": "flo_02-10-06 002",
"link": "https://...",
"media": {
"m": "https://....jpg"
},
"date_taken": "2018-11-13T12:09:32-08:00",
"description": "......"
"published": "2018-11-13T11:11:06Z",
"author": "nobody#flickr.com (\"nikita zenon2\")",
"author_id": "125437611#N07",
"tags": "some tags here"
},
I get urls but now I don't now how to show images on screen, maybe by using map function. If you know, please let me know. I'm new in ReactJs.
Thanks

You're almost there actually, you just need to nest your img tags inside of the li tags.
<!-- language: lang-js -->
render() {
const mappedStorage = this.state.images.map((item) => <li><img src={item.media.m} /></li>)
return (
<div className="fun2">
{this.state.spinner?
<div>
<MDSpinner size={50}/>
</div>
:null}
<ul>{mappedStorage}<ul>
<button onClick={this.loadimages}>
Click Here
</button>
</div>
);
}

Related

Filter JSON Array in ReactJS component

I am new to the community and English is not my native language (I speak Spanish), but I will try to ask my question as clearly as possible.
I'm learning React and I am working on a component that imports a JSON file containing an array. I'm trying to figure out how to filter the array to be able to show information according to the url patch.
File React:
import React from 'react';
import Lista from '../../Arrays/Lista';
const Card = ({ match }) => {
const product = Lista.filter( p => p.id === parseInt(match.params.id))
return (
<div>
<h1> {product.title} </h1>
<p>{product.description}</p>
<img src={product.image} alt="imagen"/>
</div>
)
}
export default Card;
File JSON:
[
{
"id": 0,
"title": "FunkoPop Woody",
"description" : "FunkoPop Woody Edicion Limitada",
"price": "11.900",
"image": "https://ripleycl.imgix.net/https%3A%2F%2Fs3.amazonaws.com%2Fimagenes-sellers-mercado-ripley%2FImagenes-MIRAKL%2FMPM00002571116%2FMPM00002571116-1-F.jpg?w=750&h=555&ch=Width&auto=format&cs=strip&bg=FFFFFF&q=60&trimcolor=FFFFFF&trim=color&fit=fillmax&ixlib=js-1.1.0&s=95653b7ade9c0f60337f9b396fc0b544"
},
{
"id": 1,
"title": "FunkoPop Stitch",
"description" : "FunkoPop Stitch Regular Edition",
"price": "9.900",
"image": "https://www.tiendawabro.com.ar/media/catalog/product/cache/1/image/1800x/040ec09b1e35df139433887a97daa66f/2/3/2353.jpg"
},
{
"id": 2,
"title": "FunkoPop Jinx",
"description": "FUnkoPop League of Legends",
"price": "10.900",
"image": "https://www.metalgame.cl/wp-content/uploads/2018/01/889698103053.jpg"
}
]

React would not access nested state

I have set React state to data from an API
this.setState({loan: response.data})
response.data is a nested object
{
application: {
amount: 20,
interest: 10,
guarantor: {
firstName: "John",
lastName: "Doe"
}
},
userId: "123"
}
Normally inside the render function i can access
<p>{this.state.loan.userId}</p>
<p>{this.state.loan.application.amount}</p>
<p>{this.state.loan.application.guarantor.firstName}</p>
Now I can only access the first child of the loan. Except i practically set the state for each individual item in the object. Note console.log(this.state.loan.application.guarantor) works fine.
This is the API call
fetch(`http://localhost:8000/api/v1/loans/${this.state.id}`)
.then(res => {
return res.json();
}).then(response => {
this.setState({loan: response.data});
})
.catch(err => console.log(err));
const {loan} = this.state;
<div className="col-md-4">
<h5 className="title">Full Name</h5>
<p>{loan.fullName}</p>
<h5 className="title mt-3">Account Number</h5>
<p>{loan.accountNumber}</p>
<h5 className="title mt-3">Phone Number</h5>
<p>Phone Number</p>
</div>
<div className="col-md-4">
<h5 className="title">Loan Amount</h5>
<p>
{(loan.application.amount).toLocaleString("en-NG", {
style: "currency",
currency: "NGN"
})}
</p>
<h5 className="title mt-3">Interest Rate</h5>
<p>{loan.interestRate}%</p>
<h5 className="title mt-3">Duration</h5>
<p>{loan.duration} Months</p>
</div>
The response from API call
{
"application": {
"guarantor1": {
"fullName": "Ayebakuro Ombu",
"residentialAddress": "30 Udengs Eradiri Avenue Off Azikoro Village Road",
"occupation": "Accountant",
"netIncome": "50000",
"placeOfWork": "Dreamworld",
"employer": "Ayebakuro Ombu",
"relationship": "Employer",
"bvn": "0101010101",
"bank": "GTBank",
"accountNumber": "10101010101",
"phoneNumber": "010101010101"
},
"guarantor2": {
"fullName": "Ayebakuro Ombu",
"residentialAddress": "B48 Copa Cobana Estate, Wumba, Lokogoma",
"occupation": "business man",
"netIncome": "500000",
"placeOfWork": "Dreamworld",
"employer": "SafeScrow Tech",
"relationship": "Employer",
"bvn": "0101010101",
"bank": "GTBank",
"accountNumber": "0101010101",
"phoneNumber": "0101010101"
},
"mode": {
"name": "DreamWorld Savings And Loans Ltd",
"address": "30 Udengs Eradiri Avenue Off Azikoro Village Road",
"netIncome": "50000"
},
"bankDetails": {
"bank": "Parallex Bank",
"accountNumber": "0101010101",
"bvn": "0101010101"
},
"amount": 200000,
"number": "25642",
"date": "2019-03-22T02:37:58.069Z",
"purpose": "For debt payment"
},
"approval": {
"amount": 0,
"status": "Pending"
},
"issue": {
"status": false
},
"payment": {
"schedule": [],
"completed": false
},
"_id": "5c944a86abf7ea09c40301e5",
"accountNumber": "1000000002",
"fullName": "Ayebakuro Ombu",
"type": "Business",
"duration": 5,
"interestRate": 10,
"__v": 0
}
The error: LoanPage.js:61 Uncaught TypeError: Cannot read property 'amount' of undefined
at LoanPage.render (LoanPage.js:61)
Logging this.state.loan.application.amount logs correctly
When a component is rendered (like the following code), React calls the render method of corresponding component immediately.
ReactDom.render(<LoanPage />, element);
Event if you were to execute a asynchronous fetch in constructor, or componentWillMount method, that wouldn't prevent the React system from executing render.
This is how you should approach this problem. In constructor / componentWillMount, you should set this.state.loading = true, and then fire the fetch call. In the .then part of fetch call, setState to clear the loading flag like this:
this.setState({
loading: false,
loan: response.data
});
The render method of LoanPage can now benefit from the knowledge of 'fetch call in progress' like this:
render() {
if(this.state.loading) {
return (<h3>Loading...</h3>);
}
return (
<div> Loan amount is {this.state.loan.application.amount} </div>
);
}
You can change the first part of render (in if condition) to display a spinner or some equivalent. You should change the second part to render everything that you are rendering now.

How to load different part of data from JSON file for each page using AngularJS?

I'm trying to create a shopping website using angularJs. My website has several html pages like women.html, men.html,...
I has 1 JSON file for the whole website. I want each website has different products, I did it but it only works on the main page (the page which showing all the products). When I click on a specific product, it doesn't show anything thing.
For more clearly, here is my code:
JSON file:
{
"Men": [
{
"name": "Adidas",
"price": 20,
"id": "adidas1",
"image": "pic4.png",
"description": "abcđsfadfdfsgsg"
},
{
"name": "Nike",
"price": 37,
"id": "nike1",
"image": "pic2.png",
"description": "abcđsfadfdfsgsg"
},
{
"name": "Converse",
"price": 25,
"id": "converse1",
"image": "pic3.png",
"description": "abcđsfadfdfsgsg"
}
],
"Women": [
{
"name": "Adidas2",
"price": 20,
"id": "adidas2",
"image": "pic6.png",
"description": "abcđsfadfdfsgsg"
},
{
"name": "Nike2",
"price": 37,
"id": "nike2",
"image": "pic7.png",
"description": "abcđsfadfdfsgsg"
},
{
"name": "Converse2",
"price": 25,
"id": "converse2",
"image": "pic5.png",
"description": "abcđsfadfdfsgsg"
}
]
}
Men.html:
<div ng-repeat="item in items.Men" style="float:left;">
<div><a href="#/item/{{item.name}}"><img src="/image/{{item.image}}" />
</a>
</div>
</div>
Women.html:
<div ng-repeat="item in items.Women" style="float:left;">
<div>
<a href="#/item/{{item.name}}"><img src="/image/{{item.image}}" />
</a>
</div>
</div>
App.js:
app.controller('ItemCtrl',
['$scope', '$routeParams', 'cartService',
function ($scope, $routeParams, cartService) {
$scope.item = {};
angular.forEach($scope.items, function (item) {
if (item.name == $routeParams.itemName) {
$scope.item.itemName = item.name;
$scope.item.itemPrice = item.price;
$scope.item.itemId = item.id;
$scope.item.itemImage = item.image;
$scope.item.itemDescription = item.description;
}
});
$scope.addProduct = function (item) {
cartService.addToCart(item, $scope.numberOfProducts);
};
}
]);
Product details page:
<div style="float:left; margin:0px 50px 300px 50px;">
<img src="/image/{{item.itemImage}}" style="margin- bottom:50px;margin-
left:200px;">
<p style="margin-right:0px;margin-top:50px;margin-left:50px;">Description:
{{item.itemDescription}}</p>
</div>
The code is really long so I only show its parts which I think making my code doesn't work.
Hopefully, there would be some help. Thanks in advance!
Check whether 'ItemCtrl' controller is binded to both men.html and women.html, if both the html files are not views.
Make two controllers and use $http method to call each page.Then using scope,reference data that you want and render in each page

Using JSONP with the flickr api

i`ve got this JSONP response from the FLICKR api and i want to creat with the "link" as the source from each of them. i try doing this but nothing happend. and i have write a
<script src = "https://api.flickr.com/services/feeds/photos_public.gne?format=json"></script>
the javascript:
function jsonFlickrFeed(data)
{
for(var a = 0 ; a < 5 ; a++)
{
var img = document.createElement(img);
img.src = data.items[i].link;
}
}
then
jsonFlickrFeed({
"title": "Uploads from everyone",
"link": "https://www.flickr.com/photos/",
"description": "",
"modified": "2015-09-22T22:17:01Z",
"generator": "https://www.flickr.com/",
"items": [
{
"title": "بالصور| أفضل الفنادق في مراكش",
"link": "https://www.flickr.com/photos/131615921#N08/21014053604/",
"media": {"m":"https://farm6.staticflickr.com/5645/21014053604_251062f1df_m.jpg"},
"date_taken": "2015-09-22T15:17:01-08:00",
"description": " <p><a href=\"https://www.flickr.com/people/131615921#N08/\">www.7aya.net<\/a> posted a photo:<\/p> <p><a href=\"https://www.flickr.com/photos/131615921#N08/21014053604/\" title=\"بالصور| أفضل الفنادق في مراكش\"><img src=\"https://farm6.staticflickr.com/5645/21014053604_251062f1df_m.jpg\" width=\"240\" height=\"149\" alt=\"بالصور| أفضل الفنادق في مراكش\" /><\/a><\/p> <p>قدم موقع التلغراف في قسمه المخصص للسفر قائمة بأفضل الفنادق في مدينة مراكش المغربية، وقد شملت القائمة الفنادق الفاخرة و الفنادق الرخيصة والفنادق الصديقة للعائلة، وبينما تظهر المزيد من الفنادق الجديدة في جميع أنحاء المدينة، تم تحويل أكثر من 200 من رياض المدينة إلى بيوت الضيافة، وفيما يلي 10 من أفض... <br /> <br /> <a href=\"http://www.7aya.net/2015/09/23/%d8%a8%d8%a7%d9%84%d8%b5%d9%88%d8%b1-%d8%a3%d9%81%d8%b6%d9%84-%d8%a7%d9%84%d9%81%d9%86%d8%a7%d8%af%d9%82-%d9%81%d9%8a-%d9%85%d8%b1%d8%a7%d9%83%d8%b4/\" rel=\"nofollow\">www.7aya.net/2015/09/23/%d8%a8%d8%a7%d9%84%d8%b5%d9%88%d8...<\/a><\/p>",
"published": "2015-09-22T22:17:01Z",
"author": "nobody#flickr.com (www.7aya.net)",
"author_id": "131615921#N08",
"tags": ""
},
{
"title": "Bebiendo #Café #cafe #café #Oaxaca #Neurona #Neuroname http://Neurona.me",
"link": "https://www.flickr.com/photos/46158081#N07/21014054554/",
"media": {"m":"https://farm6.staticflickr.com/5699/21014054554_27b54fc07f_m.jpg"},
"date_taken": "2015-09-22T17:17:04-08:00",
"description": " <p><a href=\"https://www.flickr.com/people/46158081#N07/\">puente sur<\/a> posted a photo:<\/p> <p><a href=\"https://www.flickr.com/photos/46158081#N07/21014054554/\" title=\"Bebiendo #Café #cafe #café #Oaxaca #Neurona #Neuroname http://Neurona.me\"><img src=\"https://farm6.staticflickr.com/5699/21014054554_27b54fc07f_m.jpg\" width=\"240\" height=\"240\" alt=\"Bebiendo #Café #cafe #café #Oaxaca #Neurona #Neuroname http://Neurona.me\" /><\/a><\/p> ",
"published": "2015-09-22T22:17:04Z",
"author": "nobody#flickr.com (puente sur)",
"author_id": "46158081#N07",
"tags": "square squareformat iphoneography instagramapp uploaded:by=instagram"
}]}
There's a few problems with the original code:
items[i] refers to i which is undefined since you're looping over a.
The link attribute on each data item is a link to an HTML page containing the image, not a src for the image itself. You would want to use the media attribute which is a direct link to the image.
img needs quotes when creating the image element
You never add the created element to the DOM
http://jsfiddle.net/rmuctecp/
<script>
function jsonFlickrFeed(data)
{
for(var i = 0 ; i < 5 ; i++)
{
var img = document.createElement("img");
img.src = data.items[i].media.m;
document.body.appendChild(img);
}
}
</script>
<script src = "https://api.flickr.com/services/feeds/photos_public.gne?format=json"></script>

AngularJS ngRepeat replacing bindings with nothing

I have an AngularJS app that is searching through a list of services, which then displays the results below the search bar using ngRepeat. The right amount of search results are being displayed, but the bindings are being filled with nothing, leaving the anchor tags empty.
Here is the markup being generated:
<h4 class="media-heading result-heading"></h4>
<p class="result-abstract"></p>
<p></p>
<p></p>
<div class="row">
<div class="col-all-12 result-contact">
<div class="">
<span class="icon-office"></span>
</div>
<div class="">
<span class="icon-phone"></span>
</div>
</div>
</div>
I have the exact same code running on my local machine, it works as expected, and the versions of AngularJS are the same, so I have no clue what is going on. Has anyone experienced this before, and how have hey resolved it?
No errors are thrown, the data is being retrieved via AJAX from a json file.
Here is the template with the ngRepeats in it:
<div class="media-body search-result" ng-repeat="service in services | filter: query | filterTags: allTags | orderBy: serviceOrder:direction | hasValue | startFrom:(currentPage - 1) * servicesPerPage | limitTo:servicesPerPage">
<h4 class="media-heading result-heading">{{service.serviceName}}</h4>
<p class="result-abstract">{{service.abstract}}</p>
</p>
</p>
<div class="row">
<div class="col-all-12 result-contact">
<div class="">
<span class="icon-office"></span> {{service.office}}
</div>
<div class="">
<span class="icon-phone"></span> {{service.contact}}
</div>
</div>
</div>
</div>
The code behind this isn't really all that important since it is an exact copy of everything from one page to another, and it works on the previous page. There are no differences in the HTML, CSS or Javascript, other than the fact that the markup on the new page is filled in with blanks.
I have already checked to make sure that the json data is being pulled in correctly, and that the versions of AngularJS are the same (Version is 1.2.21).
Here are the custom filters:
serviceSearchbar.filter('startFrom', function () {
return function (input, start) {
start = +start; //parse to int
return input.slice(start);
}
});
serviceSearchbar.filter('hasValue', function() {
return function (input) {
if (angular.element('#servicesQuery').val()) {
return input;
}
return [];
}
});
serviceSearchbar.filter("isSelected", function () {
return function (input) {
var response = {};
if (input !== undefined) {
Object.keys(input).forEach(function (tag) {
if (input[tag] !== false) {
response[tag] = true;
}
});
}
return response;
}
});
serviceSearchbar.filter("filterTags", ["$filter", function ($filter) {
return function (input, tags) {
var selectedTags = [],
response = input,
found = false,
numSelectedTags;
if (input === undefined) {
return input;
}
if (tags !== undefined) {
Object.keys(tags).forEach(function (tag) {
if (tags[tag] !== false) {
selectedTags.push(tag);
}
});
}
if (selectedTags.length > 0) {
response = $filter("filter")(response, function(value) {
var found = false;
selectedTags.forEach(function(tag) {
if (value.tags.indexOf(tag) !== -1) {
found = true;
return true;
}
});
return found;
});
}
return response;
}
}]);
And here is an example of the data that is being used:
{
"services": [
{
"serviceName": "Department of Art",
"sponsor": "Department of Art",
"shortName": "art-dep",
"url": "http://www.byui.edu/art/",
"contactName": "Contact Name",
"office": "Spori some room",
"contact": "(123) 456-7890",
"mapUrl": "http://www.byui.edu/maps#SPO",
"tags": [
"art",
"design",
"art department",
"art program"
],
"abstract": "The BYU-Idaho Department of Art provides an aesthetic, conceptual, and technical foundation in the visual arts for students who possess a wide range of interests, experiences, and abilities."
},
{
"serviceName": "College of Performing and Visual Arts",
"sponsor": "College of Performing and Visual Arts",
"shortName": "performing-visual-arts",
"url": "http://www.byui.edu/performing-visual-arts",
"contactName": "Contact Name",
"office": "Spori some room",
"contact": "(123) 456-7890",
"mapUrl": "http://www.byui.edu/maps#SPO",
"tags": [
"art",
"dance",
"music",
"spori",
"theater"
],
"abstract": "The College of Performing and Visual Arts provide an important means of communication where thoughts, creativity, and expression can be directed to ennoble, uplift, inspire..."
},
{
"serviceName": "Spori Art Gallery",
"sponsor": "Department of Art",
"shortName": "spo-gal",
"url": "http://www.byui.edu/spori-gallery/",
"contactName": "Contact Name",
"office": "Spori some room",
"contact": "(123) 456-7890",
"mapUrl": "http://www.byui.edu/maps#SPO",
"tags": [
"art",
"gallery",
"spori"
],
"abstract": "Jacob Spori Art Gallery will show works of current BYU-Idaho Visual Arts students, selected by the art department faculty."
}
]
}

Categories

Resources