I have js files Dashboard and Adverts. I managed to get Dashboard to list the information in one json file (advertisers), but when clicking on an advertiser I want it to navigate to a separate page that will display some data (Say title and text) from the second json file (productadverts). I can't get it to work. Below is the code for the Dashboard and next for Adverts. Then the json files
import * as React from 'react';
import { Text, View, StyleSheet, Image, FlatList, TouchableOpacity } from 'react-native';
import advertisers from '../data/advertisers.json';
export default class Advertisers extends React.Component {
rendItem = listItem => {
let item = listItem.item
return (
<TouchableOpacity onPress={() => this.advertSelected(item)}>
<Text>
{' '}{item.id}{' '}{item.company}{' '}
</Text>
</TouchableOpacity>
);
};
advertSelected = (item)=>{
this.props.navigation.navigate("Adverts",{advert:item})
}
render() {
return (
<View style={styles.container}>
<Text style={styles.title}>List of advertisers</Text>
<FlatList
style={styles.list}
data={advertisers}
renderItem={this.rendItem}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: { marginTop: 30, marginLeft: 20 },
title: { fontSize: 20 },
list: { paddingTop: 20 },
});
Adverts
import * as React from 'react';
import { Text, View, StyleSheet, Image, FlatList, TouchableOpacity } from 'react-native';
import adverts from '../data/productadverts.json';
export default class Adverts extends React.Component {
rendItem = listItem => {
let item = listItem.item
let advert = this.props.navigation.getParam("advert")
let pic = advert.picture
let title = advert.title;
let id = advert.id;
};
render() {
return (
<View style={styles.container}>
<Text style={styles.title}>List of advertisers</Text>
<FlatList
style={styles.list}
data={adverts}
renderItem={this.rendItem}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: { marginTop: 30, marginLeft: 20 },
title: { fontSize: 20 },
list: { paddingTop: 20 },
});
advertisers.json
[
{
"company": "Fujifilm",
"id": 1,
"address": "St Martins Business Centre, St Martins Way, Bedford MK42 0LF",
"contactperson": "Carrie Perrett",
"contactnumber": "01234572000",
"emailaddress": "carrie#fuji.co.uk",
"logo": "https://logos-download.com/wp-content/uploads/2016/04/Fujifilm_logo_slogan_value_from_innovation.jpg"
},
{
"company": "Boeing",
"id": 2,
"address": "25 Victoria St, Westminster, London SW1H 0EX",
"contactperson": "Joanne Cumner",
"contactnumber": "02073401900",
"emailaddress": "jo#boeing.co.uk",
"logo": "https://www.govconwire.com/wp-content/uploads/2013/06/boeing-logo.jpg"
},
{
"company": "IBM",
"id": 3,
"address": "Birmingham Rd, Warwick CV34 5AH",
"contactperson": "Allan Elborn",
"contactnumber": "01926464000",
"emailaddress": "allan#ibm.co.uk",
"logo": "https://d15shllkswkct0.cloudfront.net/wp-content/blogs.dir/1/files/2012/08/ibm-logo.jpeg"
},
{
"company": "Fujitsu",
"id": 4,
"address": "55 Jays Cl, Basingstoke RG22 4BY",
"contactperson": "Alex Taylor",
"contactnumber": "08433545555",
"emailaddress": "alex#Fujitsu.co.uk",
"logo": "https://i.pinimg.com/originals/48/dc/fc/48dcfcd5df1834f66d029d7d34fae26d.png"
}
]
productadverts.json
[
{
"title": "ICT and Fujifilm’s new wave of innovation",
"id": 1,
"text": "Taking outstanding ICT achievements to the next level. ICT continues to advance rapidly. One recent example is the Internet of Things (IoT), in which devices and appliances have Internet connectivity and ICT functions built in. Moreover, ICT appears ready to take off in industry as never before, spurred by new advances in such technologies as artificial intelligence (AI) and virtual reality (VR). Some even view these trends in ICT as having the potential to lead to a new Industrial Revolution. As a leading technology company, Fujifilm is poised to become a major creative force in ICT and drive its own wave of innovation.",
"picture": "https://2df223ae-a-62cb3a1a-s-sites.googlegroups.com/site/eportfolioduaa/home/advantages-and-disadvantages-of-i-c-t/ict%202.png?attachauth=ANoY7cpUeQC5IlBqWx_cSW5wq5f4lDOPpWph4cfUpWUbE5h-fxfKatvv_ztmibYt834f8GHLpHcgZ6yA3wmc7c7veFhbf5NMke0MAkprLtZZHdllza0Q62BOEj3SHvZMg4rGKJegcIwfb6zW8a4OqAdgqFYvU1BCtNm25YqpngDRRN0HPqt8PmulWjVk2TS4jDWOt4KZfAd9pznmf8fi3Vw-zZJ0Ne_yFRON763E-2v8YzwRFc3yui_HfDE3HsqxcF3JIOizhQSVnqnJStlxeyzTDH_1yL8iZg%3D%3D&attredirects=0",
"advertiser": "Fujifilm"
},
{
"title": "Technologies",
"id": 2,
"text": "Fujifilm is a technology company. A photography company. Although quite a few people still have this image of Fujifilm, today it’s so much more. By leveraging the technologies it originally developed for the photography industry and continuously and proactively pursuing advanced R&D, Fujifilm has created businesses in multiple high-tech fields and become a technology-oriented company. ",
"picture": "https://logos-download.com/wp-content/uploads/2016/04/Fujifilm_logo_slogan_value_from_innovation.jpg",
"advertiser": "Fujifilm"
},
{
"title": "2020 Call for Code Global Challenge",
"id": 3,
"text": "Get inspired. Join the fight. Impact the world. Congratulations to the initial COVID-19 solutions that are now receiving deployment support. They show how technology can help small businesses find assistance after a crisis, redefine the queuing experience and guide us to the right medical advice. Developers and problem solvers, remember you have until July 31 to submit your open source solutions.",
"picture": "https://res.cloudinary.com/practicaldev/image/fetch/s--YBeZKs5E--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/c5zqnlp91mjy1v4uqaog.png",
"advertiser": "IBM"
},
{
"title": "It’s not about the data – it's what you do with it!",
"id": 4,
"text": "Power your operations and gain valuable insights using data analytics. Boeing AnalytX utilizes our aerospace expertise with data-based information to give you empowered decision support to optimize your operation and mission. Applications using Boeing predictive analytics give customers a glimpse into the near-future; more time to evaluate, plan and manage solutions. Boeing AnalytX offers three interrelated categories of analytics enabled products and services customers may easily mix and match to meet needs and goals. Digital Solutions – a set of analytics enabled software applications addressing the needs of crew and fleet scheduling, flight/mission planning and operations, maintenance planning and management, and inventory and logistics management. Analytics Consulting Services – a group of aviation, business, and analytics professionals who are ready to help customers improve their operational performance, efficiency, and economy. Self-Service Analytics – our newest category, that opens up the data behind the digital solutions for customers to explore and discover new insights and opportunities using Boeing provided analytics tools. ",
"picture": "https://www.govconwire.com/wp-content/uploads/2013/06/boeing-logo.jpg",
"advertiser": "Boeing"
},
{
"title": "Rethinking business and society in times of crisis",
"id": 5,
"text": "The continued spread and effects of the Coronavirus (COVID-19) are disrupting the everyday lives of people, society and businesses alike, and triggering inevitable and reasonable concerns among us all. Alongside our ongoing commitment to supporting many of the critical systems on which the UK relies every day, we have made it a priority to look at where Fujitsu technology and innovation can support the response to COVID-19. ",
"picture": "https://i.pinimg.com/originals/48/dc/fc/48dcfcd5df1834f66d029d7d34fae26d.png",
"advertiser": "Fujitsu"
}
]
The new object to get params in React Navigation 5 is:
this.props.route.params
Try to get the advert param using:
const { advert } = this.props.route.params;
Related
I have products.json in which I have data. Now, I wish to render it using Reactjs.
products.json
[
{
"id": 1,
"productName": "Fjallraven - Foldsack No. 1 Backpack, Fits 15 Laptops",
"price": 109.95,
"description": "Your perfect pack for everyday use and walks in the forest. Stash your laptop (up to 15 inches) in the padded sleeve, your everyday",
"category": "men's clothing",
"image": "https://fakestoreapi.com/img/81fPKd-2AYL._AC_SL1500_.jpg",
"specification": {}
},
{
"id": 2,
"productName": "Mens Casual Premium Slim Fit T-Shirts ",
"price": 22.3,
"description": "Slim-fitting style, contrast raglan long sleeve, three-button henley placket, light weight & soft fabric for breathable and comfortable wearing. And Solid stitched shirts with round neck made for durability and a great fit for casual fashion wear and diehard baseball fans. The Henley style round neckline includes a three-button placket.",
"category": "men's clothing",
"image": "https://fakestoreapi.com/img/71-3HjGNDUL._AC_SY879._SX._UX._SY._UY_.jpg",
"specification": {}
}
]
app.js
function App(){
return(
)
}
I want the json data to be rendered through app.js.
My Take On:
I'm new to Reactjs and JSON and was thinking of using fetch, response but I'm not sure how can I do it.
Can someone please help?
First you have to put your data in variable
For example:
const data = [
{
"id": 1,
"productName": "Fjallraven - Foldsack No. 1 Backpack, Fits 15 Laptops",
"price": 109.95,
"description": "Your perfect pack for everyday use and walks in the forest. Stash your laptop (up to 15 inches) in the padded sleeve, your everyday",
"category": "men's clothing",
"image": "https://fakestoreapi.com/img/81fPKd-2AYL._AC_SL1500_.jpg",
"specification": {}
},
{
"id": 2,
"productName": "Mens Casual Premium Slim Fit T-Shirts ",
"price": 22.3,
"description": "Slim-fitting style, contrast raglan long sleeve, three-button henley placket, light weight & soft fabric for breathable and comfortable wearing. And Solid stitched shirts with round neck made for durability and a great fit for casual fashion
wear and diehard baseball fans. The Henley style round neckline includes a three-button
placket.",
"category": "men's clothing",
"image": "https://fakestoreapi.com/img/71-3HjGNDUL._AC_SY879._SX._UX._SY._UY_.jpg",
"specification": {}
}
]
The you have to map through your array
Like this
function App(){
return (
<div>
{data.map((d) => (
<div key={d.id}>
<p>ID: {d.id}</p>
<p>Product Name: {d.productName}</p>
<p>Price: {d.price}</p>
<p>Description: {d.description}</p>
<p>Category: {d.category}</p>
<p>
Image: <img src={d.image} width="100" />
</p>
<br />
<br />
</div>
))}
</div>
);
}
Then you can add CSS to make it look better!
I'm creating an app in React and trying to get data from object via function for rendering.
However, I'm getting errors and I banged my head on this for many hours but failed.
Help will be really appreciated.
I'm getting the following error:
TypeError: Cannot read property 'title' of undefined
I'm pasting the code below (Please see my comments inline):
render() {
return (
<div aria-live="assertive">
<h2>Headlines</h2>
<ul>
{
Object.values(this.state.news).map((item) => {
console.log(item[0].title); //Doesn't work however:
console.log(item[0]); //This works and prints the object to the console properly.
})
}
</ul>
</div>
}
And here is the object structure:
{
"id": 36174,
"user_id": 1,
"feed_id": 6,
"status": "unread",
"hash": "e953071e47ce854a03508542f4f4eab471a386fd5fa200600486663c56240965",
"title": "SC junks plea seeking return of MPLAD funds donated to PM CARES Fund during COVID-19 pandemic",
"url": "https://www.firstpost.com/india/sc-junks-plea-seeking-return-of-mplad-funds-donated-to-pm-cares-fund-during-covid-19-pandemic-9311531.html",
"comments_url": "",
"published_at": "2021-02-16T20:07:56+05:30",
"created_at": "2021-02-16T18:29:32.804004+05:30",
"content": "<p>The Supreme Court Tuesday dismissed a plea seeking direction to the Centre to return Rs 365 crore donated by MPs from MPLADS fund to PM CARES Fund for tackling exigencies emerging from the COVID-19 pandemic.</p><p>A bench of Chief Justice Bobde and Justices AS Bopanna and V Ramasubramanian said it is not inclined to entertain the petition and dismissed it.</p><p>Advocate Dushyant Tiwari, appearing for petitioner Tushar Gupta, said that Rs 365 crore were donated by lawmakers from Members of Parliament Local Area Development Scheme (MPLADS) in the PM CARES Fund, in contravention of the guidelines.</p><p>Tiwari referred the RTI reply to buttress his claims and said that development work was hampered due to the diversion of the funds.</p><p>The plea filed by Gupta sought appropriate direction to the central government to return the entire donated amount in the bank account in which MPLADS funds are transferred every year.</p><p>The scheme's objective is to enable MPs to recommend developmental work "with emphasis on the creation of durable community assets based on the locally felt needs to be taken up in their Constituencies, the plea said.</p><p>It said that right from inception of the scheme, durable assets of national priorities -- drinking water, primary education, public health, sanitation and roads -- are being created.</p><p>It is pertinent to note that in the month of March 2020, various MP's have donated MPLAD Fund for the pandemic and as per information a total number of 339 MP's have contributed a total of Rs 365 crore from their MPLADS to the Central pool for measures towards tackling exigencies in India emerging from the effect of the pandemic, the plea added.</p><p>The petition said that in April 2020 the MPLADS funds were suspended for two financial years -- 2020-2021 and 2021-2022.</p><p>Gupta referred to the RTI reply and said it raised few important questions and doubts related to the donation of the MPLAD Fund for the purpose of COVID-19.</p><p>The plea sought direction to the MPs to re-prioritise the earlier recommended works so that the incomplete work can be completed from the un-utilised amount available with the district authority.</p>",
"author": "Press Trust of India",
"share_code": "",
"starred": false,
"reading_time": 2,
"feed": {
"id": 6,
"user_id": 1,
"feed_url": "https://www.firstpost.com/rss/india.xml",
"site_url": "https://www.firstpost.com/category/india",
"title": "Firstpost India News",
"checked_at": "2021-02-16T18:29:32.331595+05:30",
"next_check_at": "0001-01-01T00:00:00Z",
"etag_header": "",
"last_modified_header": "",
"parsing_error_message": "",
"parsing_error_count": 0,
"scraper_rules": "",
"rewrite_rules": "",
"crawler": false,
"blocklist_rules": "",
"keeplist_rules": "",
"user_agent": "",
"username": "",
"password": "",
"disabled": false,
"ignore_http_cache": false,
"fetch_via_proxy": false,
"category": {
"id": 5,
"title": "India News",
"user_id": 1
},
"icon": {
"feed_id": 6,
"icon_id": 5
}
}
}
So, here I'm unable to identify that if the complete object is being printed out in the console by using the second line (Please refer the code above) then why it is giving the error in first console.log call.
Please help
The corresponding map function is working with only with arrays. U are trying to output normal objects. Just Add
<ul> {title} </ul>
<ul> {feed.title} </ul>
I'm working on a React project that'll allow me to search through a list of games to help me decide what to play based on what I'm in the mood for, currently I can add games to a JSON file but I'm really struggling with the searching part.
Right now, to add a new game, you'll enter the title, genre(s) and a description of the game. The genre field is a ReduxForm FieldArray object, and I think that's what's giving me the trouble. Here's my current JSON file
{
"games": [
{
"name": "Rainbow Six: Siege",
"genres": [
{
"genre": "tactical"
},
{
"genre": "shooter"
}
],
"description": "tactical team based shooter",
"id": 1
},
{
"name": "Resident Evil 2",
"genres": [
{
"genre": "horror"
},
{
"genre": "survival"
},
{
"genre": "shooter"
}
],
"description": "classic resident evil 2 remake in 2019",
"id": 2
},
{
"name": "Rocket League",
"genres": [
{
"genre": "cars"
},
{
"genre": "competition"
},
{
"genre": "one more game"
}
],
"description": "soccar!",
"id": 3
}
]
}
This is the dummy data I'm using to search:
const searchedGenres = 'horror, shooter';
const searchedList = searchedGenres.split(', ');
let foundGame = [];
Once I get the search working with this data, the plan is to allow me to just type in data on the frontend in one textbox, so "horror, shooter" would be my search term. The result from this search should only return Resident Evil 2, however I'm also receiving Rainbow Six: Siege as a result, even though it's missing one of my requested genres.
searchedList.forEach(searchedGenre => {
this.props.games.map(game => {
if (
game.genres.find(
({ genre }) =>
genre.toLowerCase() ===
searchedGenre.toLowerCase().trim()
) !== undefined
) {
foundGames.push(game);
}
});
});
I understand why I'm getting both Rainbow Six and Resident Evil as a result, because I'm not actually checking that both genres are in the games genres when I add the game to the foundGames array, but I'm completely lost on how I'd go about making sure all of the genres are in a game before I add it.
This would be a bit easier if your genres was a simple array of strings rather than objects, but still you can check pretty succinctly by leveraging some() and every() within filter() (btw filter() is a better choice than map() + push() here)
let games = [{"name": "Rainbow Six: Siege","genres": [{"genre": "tactical"},{"genre": "shooter"}],"description": "tactical team based shooter","id": 1},{"name": "Resident Evil 2","genres": [{"genre": "horror"},{"genre": "survival"},{"genre": "shooter"}],"description": "classic resident evil 2 remake in 2019","id": 2},{"name": "Rocket League","genres": [{"genre": "cars"},{"genre": "competition"},{"genre": "one more game"}],"description": "soccar!","id": 3}]
const searchedGenres = 'horror, shooter';
const searchedList = searchedGenres.split(', ');
let foundGame = games.filter(game => searchedList.every(searchItem => game.genres.some(g => g.genre == searchItem) ))
console.log(foundGame)
The filter condition basically says you want every game in searchedList to match at least one genre in the game. This will make it only return games that match every genre.
I have a local .json file formated below
{
"results": [
{
"id": 1,
"title": "2 bedroom apartment to rent",
"location": "30 South Colonnade London E14 5EZ",
"description": "The building offers a communal lifestyle which consists of a large lounge area with dining room, working space, TV lounge, gym, stylish meeting rooms, free table tennis, free WIFI and a spacious communal roof terrace. Local transport includes Canning Town DLR and Jubilee Line (0.1 miles). Argo Apartments is managed by Grainger plc, one of the UK's leading professional landlords with over 100 years experience.",
"price": "1,800",
"beds": 2,
"bathrooms": 1,
"landlord": "Hamptons International Lettings",
"images": ["image1", "image2"]
},
{
"id": 2,
"title": "2 bedroom flat to rent",
"location": "Textile Building, Chatham Place, Hackney, London, E9",
"description": "SHORT LET - Forming part of the new eagerly awaited Textile Building in Hackney Central E8, this stunning two double bedroom property has been finished to the highest standard, featuring two modern fitted bathrooms (one en-suite), two equal double bedrooms, spacious open plan reception with brand new integrated kitchen, exposed brickwork and communal underground bike storage.",
"price": "2,400",
"beds": 2,
"bathrooms": 1,
"landlord": "Stirling Ackroyd, Hackney",
"images": ["image1", "image2"]
},
{
"id": 3,
"title": "3 bedroom apartment to rent",
"location": "Sixth Floor Tower Building 11 York Road London SE1 7NX",
"description": "A fantastic three bedroom apartment set in this popular development close to Vauxhall and Stockwell tube stations. The apartment is neutrally decorated throughout and is available either furnished or unfurnished. Residents will enjoy the plethora of shops, bars and restaurants and leisure activities in this popular part of London as well as the excellent commuter links towards Central London.",
"price": "2,050",
"beds": 3,
"bathrooms": 2,
"landlord": "Regent Letting and Property Management",
"images": ["image1", "image2"]
}
],
"newResults" : [
{
"id": 4,
"title": "2 bedroom flat to rent",
"location": "Conway Street, Fitzrovia, W1T",
"description": "Complete is delighted to market this newly renovated period property situated on the corner of Fitzroy Square in the heart of Fitzrovia, W1. The property is located on the ground floor and comes with 2 double bedrooms, shower room, open plan living and kitchen area. The kitchen is fully fitted with Siemens appliances and Duravit fittings in the bathroom. This apartment has high ceiling and retains its original period features. Located on the corner of this garden square this development was built in the 18th Century and benefits from being in the heart of vibrant London whilst also being a quiet residential area.",
"price": "1,500",
"beds": 2,
"bathrooms": 1,
"landlord": "Barnard Marcus Lettings",
"images": ["image1", "image2"]
}
]
}
I want to be able to call the relevent information mapped to a component as below
class ResultsLists extends React.Component {
constructor(props) {
super(props)
this.state = {
results: resultsData
}
}
render() {
const results = this.state.results.results.map((result) =>
<li>{result}</li>
);
return (
<div className="rst-List">
<ul className="rst-List_Items">
{results}
</ul>
</div>
)
}
}
I can't seem to get it too work and am getting the error - Objects are not valid as a React child. There seems to be a varying variety as to why this isn't working, wondered whether someone could sanity check.
You're mapping over the results, but then you're putting the whole result object into the JSX.
This is an example of how to map over data:
const someData = [{ name: "Colin" }, { name: "Ricardo" }];
const App = () => {
const temp = someData.map(o => <li>{o.name}</li>);
return (
<div>
<ul>{temp}</ul>
</div>
);
};
Note that we have {o.name} and not just {o}.
Working example here.
So in your case, you need something like:
const results = this.state.results.results.map((result) =>
<li>{result.title}</li>
);
All aliexpress cash back websites, automatically get user order after each purchase. How they do that?
Via API i can get all my affiliate orders (orders which makes after visit my generated URL) and I can get list of them using API response:
http://gw.api.alibaba.com/openapi/param2/2/portals.open/api.getCompletedOrders/[my_app_id]?appSignature=[my_app_signature]&startDate=2017-04-01&endDate=2017-04-24&liveOrderStatus=pay
and get:
{
"result": {
"totalResults": "-",
"orders": [{
"orderTime": "04-23-2017 00:20",
"orderNumber": 83426736718999,
"product": "Humor Bear Boys Clothing Sets Brand Boys Clothes 2017 Summer Fashion Style T-Shirts+Stripe Pant 2PCS Boys Clothes",
"orderStatus": "Completed Payments",
"commissionRate": "8.0%",
"paymentAmount": "8.25",
"estimatedCommission": "0.66",
"finalPaymentAmount": "0.00",
"commission": "0.00",
"extraParams": "{}",
"trackingId": "smartbuy",
"pid": "888445371"
}]
},
"errorCode": 20010000
}
but I don't know which user make this order. Thank you!