Images show up as '[object HTMLImageElement] ' in React - reactjs

I have a drop-down auto search component built using react, the problem is that it does not allow for images currently. Here is a sample of how the code works and what the problem is in this 22-second video:
https://www.youtube.com/watch?v=kSAbTiHEJhM&feature=youtu.be
In the video when I type Caleb it shows up as Caleb [object HTMLImageElement] instead of Caleb with the image next to it.
Not sure how to implement this but my first guess is adding image to state, however I am not sure exactly where to add it in the rest of the code or even what I would set the image state too.
The AutoCompleteText.js has all the functionality in it whereas countries.js is just a list of countries with a name and an image added on to the end to test the functionality.
AutoCompleteText.js
import React from 'react';
import './AutoCompleteText.css';
export default class AutoCompleteText extends React.Component {
constructor (props) {
super(props);
this.state = {
suggestions: [],
text: ''
};
}
onTextChanged = (e) => {
const { items } = this.props;
const value = e.target.value;
let suggestions = [];
if(value.length > 0) {
const regex = new RegExp(`^${value}`, 'i');
suggestions = items.sort().filter(v => regex.test(v));
}
this.setState(() => ({ suggestions, text: value}));
}
suggestionSelected (value) {
this.setState(() => ({
text: value,
suggestions: [],
}))
}
renderSuggestions () {
const { suggestions } = this.state;
if(suggestions.length === 0) {
return null;
}
return (
<ul>
{suggestions.map((item) => <li onClick={() => this.suggestionSelected(item)}>{item}</li>)}
</ul>
);
}
render () {
const { text } = this.state;
return (
<div className="AutoCompleteText">
<input value={text} onChange={this.onTextChanged} type="text" />
{this.renderSuggestions()}
</div>
)
}
}
countries.js
const image = new Image();
image.src = '../images/myself.jpg'
export default `Afghanistan
Albania
Algeria
Andorra
Angola
Antigua & Deps
Argentina
Armenia
Australia
Austria
Azerbaijan
Bahamas
Bahrain
Bangladesh
Barbados
Belarus
Belgium
Belize
Benin
Bhutan
Bolivia
Bosnia Herzegovina
Botswana
Brazil
Brunei
Bulgaria
Burkina
Burundi
Cambodia
Cameroon
Canada
Cape Verde
Central African Rep
Chad
Chile
China
Colombia
Comoros
Congo
Congo {Democratic Rep}
Costa Rica
Croatia
Cuba
Cyprus
Czech Republic
Denmark
Djibouti
Dominica
Dominican Republic
East Timor
Ecuador
Egypt
El Salvador
Equatorial Guinea
Eritrea
Estonia
Ethiopia
Fiji
Finland
France
Gabon
Gambia
Georgia
Germany
Ghana
Greece
Grenada
Guatemala
Guinea
Guinea-Bissau
Guyana
Haiti
Honduras
Hungary
Iceland
India
Indonesia
Iran
Iraq
Ireland {Republic}
Israel
Italy
Ivory Coast
Jamaica
Japan
Jordan
Kazakhstan
Kenya
Kiribati
Korea North
Korea South
Kosovo
Kuwait
Kyrgyzstan
Laos
Latvia
Lebanon
Lesotho
Liberia
Libya
Liechtenstein
Lithuania
Luxembourg
Macedonia
Madagascar
Malawi
Malaysia
Maldives
Mali
Malta
Marshall Islands
Mauritania
Mauritius
Mexico
Micronesia
Moldova
Monaco
Mongolia
Montenegro
Morocco
Mozambique
Myanmar, {Burma}
Namibia
Nauru
Nepal
Netherlands
New Zealand
Nicaragua
Niger
Nigeria
Norway
Oman
Pakistan
Palau
Panama
Papua New Guinea
Paraguay
Peru
Philippines
Poland
Portugal
Qatar
Romania
Russian Federation
Rwanda
St Kitts & Nevis
St Lucia
Saint Vincent & the Grenadines
Samoa
San Marino
Sao Tome & Principe
Saudi Arabia
Senegal
Serbia
Seychelles
Sierra Leone
Singapore
Slovakia
Slovenia
Solomon Islands
Somalia
South Africa
South Sudan
Spain
Sri Lanka
Sudan
Suriname
Swaziland
Sweden
Switzerland
Syria
Taiwan
Tajikistan
Tanzania
Thailand
Togo
Tonga
Trinidad & Tobago
Tunisia
Turkey
Turkmenistan
Tuvalu
Uganda
Ukraine
United Arab Emirates
United Kingdom
United States
Uruguay
Uzbekistan
Vanuatu
Vatican City
Venezuela
Vietnam
Yemen
Zambia
Zimbabwe
Caleb ${image}`.split('\n')

This is happening because you are concatenating image object with the string.
Check the output below:-
const image = new Image();
image.src = '../images/myself.jpg';
var arr = [`Caleb ${image}`.split('\n')];
console.log(arr[0])
If you want to show country name followed by image url in the list then try
`Caleb ${image.src}`.split('\n')
You can't display image in the list directly using this way.
If you want to show image followed by string then use <img> tag.
let image = '<img src="https://static.daniweb.com/avatars/avatar747225.gif" />';
var country = `Celeb ${image}`;
document.getElementById('country').innerHTML = country
<ul>
<li id="country">sadfa</li>
</ul>

Related

Trying to scrape onto next web page

This is the code that i have so far
for page in range(1, 5):
guitarPage
=requests.get('https://www.guitarguitar.co.uk/guitars/electric/page-'.format(page)).text
soup = BeautifulSoup(guitarPage, 'lxml')
# row = soup.find(class_='row products flex-row')
guitars = soup.find_all(class_='col-xs-6 col-sm-4 col-md-4 col-lg-3')
This is the actual loop to iterate over the products
for guitar in guitars:
title_text = guitar.h3.text.strip()
print('Guitar Name: ', title_text)
price = guitar.find(class_='price bold small').text.strip()
print('Guitar Price: ', price)
time.sleep(0.5)
The code so far only, runs through the same page, without moving on to the next page.
The structure of the URL of the website works around page-2,page-3 ++ and so on.
You have to add {} to your link. I have added also time module.
import requests
from bs4 import BeautifulSoup
import time
for page in range(1, 5):
guitarPage = requests.get('https://www.guitarguitar.co.uk/guitars/electric/page-{}'.format(page)).text
soup = BeautifulSoup(guitarPage, 'lxml')
# row = soup.find(class_='row products flex-row')
guitars = soup.find_all(class_='col-xs-6 col-sm-4 col-md-4 col-lg-3')
for guitar in guitars:
title_text = guitar.h3.text.strip()
price = guitar.find(class_='price bold small').text.strip()
print('Guitar Name: ', title_text, 'Guitar Price: ', price)
time.sleep(0.5)

How do I sort and display a React array by year and month?

I'm fairly new to React. Basically I'm trying to display a table of receipts with the following attributes for each receipt:
{
date: '2017-07-03',
description: 'Receipt description,
amount: 300
}
I'm trying to split and order the receipts into sections as follows:
2017
July
03 Jul | Receipt Description | £300.00
------ | ------------------- | -------
01 Jul | Receipt Description | £20.00
May
03 May | Receipt Description | £300.00
------ | ------------------- | -------
01 May | Receipt Description | £20.00
2016
...
I can easily map over the objects and sort the by date but can't figure out how to split them into the year and month sections. Any guidance would be appreciated greatly!
You could do something like that:
var sorted = data.sort(function(a, b) {
return new Date(a.date) - new Date(b.date);
});
var byYearAndByMonth = {};
_.each(sorted, function(item) {
var year = item.date.substring(0,4)
var month = item.date.substring(5,7)
if (typeof byYearAndByMonth[year] === "undefined") {
byYearAndByMonth[year] = {};
}
if (typeof byYearAndByMonth[year][month] === "undefined") {
byYearAndByMonth[year][month] = [];
}
byYearAndByMonth[year][month].push(item);
});
First you sort the array, then you loop over the sorted array and build an object index by year an month.
Then to map over the object in your render() method you'll have to use Object.keys
See this jsfiddle

Build custom input field list with display field from associated model in cakephp 3

I have three tables campaign_social_accounts, social_accounts, and social_networks
SocialNetworks contains are networks which user can connect to with columns as
+-----+--------+
| id | title |
+-----+--------+
SocialAccounts has the all accounts user is connected to with columns as
+----+---------+-------------------+--------------+----------+
| id | user_id | social_network_id | access_token | user_key |
+----+---------+-------------------+--------------+----------+
CampaignSocialAccounts has association of Campaigns and added social accounts to that campaign
+-----+-------------+-------------------+
| id | campaign_id | social_account_id |
+-----+-------------+-------------------+
In add() of CampaignSocialAccounts I want user to select from SocialAccounts for that, this is what I have done in controller
$socialAccounts = $this->CampaignSocialAccounts->SocialAccounts->find('list', [
'conditions' => [
'user_id' => $this->Auth->user('id')
]
]);
and add.ctp
echo $this->Form->control('social_account_id', ['options' => $socialAccounts]);
Question
This shows id in the list as there is no other column in that field that can be set to displayField()
Also, I want to display list somewhat like
Facebook(112233445566)
Youtube(2233112233)
Where Facebook and Youtube are title from SocialNetworks table and (112233....) is user_key from SocialAccounts and the value of the option generated will be the id of the SocialAccounts
<option value="1<id from social_accounts>">Facebook(112233445566)</option>
<option value="2<id from social_accounts>">Youtube(2233112233)</option>
Is it possible, if yes, what is the best and simple approach to do this.
Edit 2: My Try
In controller action
$socialAccounts = $this->CampaignSocialAccounts->SocialAccounts
->find('list', ['valueKey' => 'social_account_title'])
->contain(['SocialNetworks'])
->where(['user_id' => $this->Auth->user('id')]);
SocialAccount.php entity
public function _getSocialAccountTitle()
{
if (isset($this->social_network)) {
return $this->social_network->title.' ('.$this->user_key.')';
}
return $this->id;
}
Still no effect
in your SocialAccounts Entity you can define a virtual property
public function _getFullName()
{
if(isset($this->social_network))
return $this->social_network->name.' ('.$this->user_key.')';
return $this->id;
}
then tu can use your new virtual property in the find() call
in your controller
$socialAccounts = $this->CampaignSocialAccounts->SocialAccounts
->find('list', ['valueField' => 'full_name'])
->contain(['SocialNetworks'])
->where(['user_id' => $this->Auth->user('id')]);

JSON-LD for more products in one page

If I have more products in one page, how can I set JSON-LD?
<article>
Our car dealership is here to make sure your vehicle always performs at its best. We provide a diverse range of services to the manufacturer’s high standard, and you’ll receive a nu.....
</article>
<article>
ALFA ROME 2.0
<img ... />
</article>
<article>
ALFA ROME 3.0
<img ... />
<img ... />
</article>
yes i want use schema.org.
i have tried to do this for each car:
<script type="application/ld+json">
{
"#context":"http://schema.org",
"#type":"Car",
"name": "Alfa Romeo Giulietta 1.6 JTDm",
"model": "Giulietta",
"brand":"alfa romeo",
"fuelType":"Diesel",
"vehicleEngine":"Diesel - 4 cilindri in linea - Cilindrata: 1598 cm3 - 4 Valvole per cilindro - Sovralimentato - Potenza max: 88 kw (120CV) a 4.000 giri/min - Coppia max 32,6 kgm (320,0 Nm) a 1.750 giri/min - Euro 6 (715/2007 - 692/2008) - Potenza Fiscale 17 CV",
"description" : "Alfa Romeo Giulietta 1.6 JTDm - 2 120 CV Distinctive (05/2015)",
"image":"assets/img/annunci/alfa-romeo-giulietta-distinctive.jpg",
"offers":{
"#type": "Offer",
"priceCurrency": "EUR",
"price": "20.850"
}
}
</script>
<script type="application/ld+json">
{
"#context":"http://schema.org",
"#type":"Car",
"name": "FIAT Nuova Panda ",
"model": "new panda",
"brand":"fiat",
"fuelType":"Benzina",
"vehicleEngine":"Benzina - 4 cilindri in linea - Cilindrata: 1242 cm3 - 2 Valvole per cilindro - Potenza max: 51 kw (69CV) a 5.500 giri/min - Coppia max 20,4 kgm (102,0 Nm) a 3.000 giri/min - Euro 6 (715/2007 - 692/2008) Potenza Fiscale 14 CV",
"description" : "FIAT Nuova Panda 1.2 Lounge (07/2014)",
"image":"assets/img/annunci/fiat-500-x-1.6-pop-star.jpg"
}
</script>
....
but is correct (if one page have more car)? the real page is auto-calanca.it/promozioni.

Show Post with its comments using ng-repeat not working

I am facing an issue in building below format in MVC using AngularJS
I am showing the posts from the facebook using api with ng-repeat which consists of a Image.
Now the problem i am facing to show the comments for each of the posts using nested ng-repeat.
Dont have any idea how to proceed with it.
ng-repeat nested sample
http://plnkr.co/edit/NGWOZ4?p=info
I think you need something like that?
<body ng-controller="programController">
<div class="panel-group" ng-repeat="row in osk.programs">
<div>{{row.day}}</div>
<div>
<h4>{{row.head}}</h4>
<p>{{row.content}}</p>
<aside class="warning" ng-repeat="row in row.extra">
<strong>Ekstra Gezi:</strong> {{row.exhead}} <span>{{row.price}}</span>
<p>{{row.excontent}}</p>
</aside>
</div>
</div>
</body>
var myApp = angular.module('myApp', []);
myApp.controller('programController', function($scope) {
var json = {
"programs":
[
{
"day":"1.GÜN",
"head":"İstanbul-Amsterdam",
"content":"Gezimizin ilk günü, kalkıştan iki saat önce Sabiha Gökçen Havalimanı Dış Hatlar Terminali Etstur Kontuarı önünde buluşarak başlıyor. Pegasus Hava Yolları tarifeli seferi ile Amsterdam’a uçuş. Havalimanında bizleri bekleyen otobüsümüz ile Amsterdam şehir turu. Bu gezide Tarihi Tren İstasyonu, Dam Meydanı, Ajax Arena Stadı, Tarihi Çiçek Pazarı ve yel değirmenleri görülecek yerlerden bazıları. Misafirlerimiz ekstra olarak düzenlenecek Amsterdam Kanallar Gezisi'ne katılabilirler. Şehir turu sonrası otele transfer. Öğleden sonra serbest zaman. Geceleme otelimizde.",
"extra":
[
{
"exhead":"Amsterdam kanallar gezisi",
"price":"55 Euro",
"excontent":"Amsterdam’a farklı açıdan bakmak isteyenler için üzeri cam olan teknelerle Amsterdam’ın simgesi haline gelmiş kanalları arasında eğlenceli gezi sizi bekliyor."
},
{
"exhead":"Tekne Turu",
"price":"15 Euro",
"excontent":"Amsterdam’a farklı açıdan bakmak isteyenler için üzeri"
}
]
},
{
"day":"2.GÜN",
"head":"Amsterdam-Paris",
"content":"Gezimizin ilk günü, kalkıştan iki saat önce Sabiha Gökçen Havalimanı Dış Hatlar Terminali Etstur Kontuarı önünde buluşarak başlıyor. Pegasus Hava Yolları tarifeli seferi ile Amsterdam’a uçuş. Havalimanında bizleri bekleyen otobüsümüz ile Amsterdam şehir turu. Bu gezide Tarihi Tren İstasyonu, Dam Meydanı, Ajax Arena Stadı, Tarihi Çiçek Pazarı ve yel değirmenleri görülecek yerlerden bazıları. Misafirlerimiz ekstra olarak düzenlenecek Amsterdam Kanallar Gezisi'ne katılabilirler. Şehir turu sonrası otele transfer. Öğleden sonra serbest zaman. Geceleme otelimizde.",
"extra":
[
{
"exhead":"Amsterdam kanallar gezisi",
"price":"55 Euro",
"excontent":"Amsterdam’a farklı açıdan bakmak isteyenler için üzeri cam olan teknelerle Amsterdam’ın simgesi haline gelmiş kanalları arasında eğlenceli gezi sizi bekliyor."
},
{
"exhead":"Tekne Turu",
"price":"15 Euro",
"excontent":"Amsterdam’a farklı açıdan bakmak isteyenler için üzeri"
}
]
}
]
};
$scope.osk = json;
});

Resources