Dynamic react routes from JSON object - reactjs

I am new to React and trying to learn the react-router. I can loop through the JSON object using the map method. But I am struggling to find a way to display the component based on each iteration. Like if the name is displayed, I want to display another array of objects in that particular iteration. I tried looking at the switch but I can't understand. Please help!!
render() {
return this.props.topic.map(t => (
<ul>
<li>
<Link to={`${t.name}`}>{t.name}</Link>
</li>
</ul>
));
<Switch>
<Route path="/:id" children={<Child />} />
</Switch>
}
This is the JSON object
topics = [
{
name: 'React Router',
id: 'react-router',
description: 'Declarative, component based routing for React',
resources: [
{
name: 'URL Parameters',
id: 'url-parameters',
description: "URL parameters are parameters whose values are set
dynamically in a page's URL. This allows a route to render the same
component while passing that component the dynamic portion of the
URL so it can change based off of it.",
url: 'https://tylermcginnis.com/react-router-url-parameters/'
},
{
name: 'Programmatically navigate',
id: 'programmatically-navigate',
description: "When building an app with React Router, eventually
you'll run into the question of navigating programmatically. The
goal of this post is to break down the correct approaches to
programmatically navigating with React Router.",
url: 'https://tylermcginnis.com/react-router-programmatically-
navigate/'
}
]
},
{
name: 'React.js',
id: 'reactjs',
description: 'A JavaScript library for building user interfaces',
resources: [
{
name: 'React Lifecycle Events',
id: 'react-lifecycle',
description: "React Lifecycle events allow you to tie into specific
phases of a component's life cycle",
url: 'https://tylermcginnis.com/an-introduction-to-life-cycle-
events-in-react-js/'
},
{
name: 'React AHA Moments',
id: 'react-aha',
description: "A collection of 'Aha' moments while learning React.",
url: 'https://tylermcginnis.com/react-aha-moments/'
}
]
},
{
name: 'Functional Programming',
id: 'functional-programming',
description: 'In computer science, functional programming is a
programming paradigm—a style of building the structure and elements of
computer programs—that treats computation as the evaluation of
mathematical functions and avoids changing-state and mutable data.',
resources: [
{
name: 'Imperative vs Declarative programming',
id: 'imperative-declarative',
description: 'A guide to understanding the difference between
Imperative and Declarative programming.',
url: 'https://tylermcginnis.com/imperative-vs-declarative-
programming/'
},
{
name: 'Building User Interfaces with Pure Functions and Function
Composition',
id: 'fn-composition',
description: 'A guide to building UI with pure functions and
function composition in React',
url: 'https://tylermcginnis.com/building-user-interfaces-with-pure-
functions-and-function-composition-in-react-js/'
}
]
}
]

Related

How to display only 4 items per page from an array react and express

I need quick help with React and Express. I have an array of data at my express server and fetched with react hooks useEffect. Currently, the response shows all the data on the same page, I want to display only 4 items per page? My React component has useState, useEffect and the JSX as normal. See my code below from Express. Any kind of help will be nice, thanks.
An array of data on Express server:
app.get('/api/surveyoptions', (req, res) => {
const surveyOptions = [
// { id: 5, title: "How often do you eat meat and dairy?" },
{ id: 1, name: "diet", label: "daily1", value: "daily1"},
{ id: 2, name: "diet", label: "daily2", value: "daily2" },
{ id: 3, name: "diet", label: "daily3", value: "daily3" },
{ id: 4, name: "diet", label: "daily4", value: "daily4" },
{ id: 5, name: "diet", label: "daily5", value: "daily5"},
{ id: 6, name: "diet", label: "daily6", value: "daily6" },
{ id: 7, name: "diet", label: "daily7", value: "daily7" },
{ id: 8, name: "diet", label: "daily8", value: "daily8" }
]
res.json(surveyOptions)
})
Not sure what your backend setup is and what database you're using, but in general you do something like this:
On frontend you make a request to the api, including the number of the page you need as a query parameter (e.g. you request '/api/surveyoptions?page=3').
*There are different styles of pagination: some prefer page number, some limit/offset. It really depends on the backend/database/etc. For short explanation of each style you can check this django-rest-framefork doc for example.
Server reads query params, finds pagination-related ones (e.g. we sent page=3, now server knows that we want the 3rd page of results), paginates results and send it back to the client. Server also should know how many items per page you want, or it could be a constant (e.g. always 10 items per page). Applying to your example, server would split surveyOptions array into chunks (10 items per chunk), and send you the 3rd one.
In react you store the page number in state, update it when user selects another page and sent along with the request as described in the first step.

React Structured Data with graphql query

Has anyone tried to implement this in a react project? There is not much in the documentation on the github/npm website. When I am trying to inject data is there a specific way to add graphql data?
JSX:
<JSONLD>
<Generic jsonldtype="event" schema={{
name: "${adv_event.title}",
description: "${adv_event.body}",
startDate: "YYYY-MM-DDT:HH:MM",
endDate: "YYYY-MM-DDT:HH:MM",
image: "",
}}>
<Generic type="location" jsonldtype="Place" schema={{ name: "test", }}/>
</Generic>
</JSONLD>
What I have tried:
name: "${adv_event.title}",
name: "`${adv_event.title}`",
name: {adv_event.title},
I was going to delete the post but, if any others are looking for this question in the future:
Answer is
name: `${adv_event.title}`,

Dynamic number of screens in TabNavigator

Situation
I currently write a news reader app for a magazine, which publishes the content in English and German under different categories. The number of categories per language is different. The categories are stored in as an array per language.
CATEGORIES_EN = [
{
selector: '*',
blog: BLOG_EN,
id: `${BLOG_EN}_*`,
},
{
selector: 'Politics',
blog: BLOG_EN,
id: `${BLOG_EN}_Politics`,
},
// ... 8 more
];
CATEGORIES_DE = [
{
selector: '*',
blog: BLOG_DE,
id: `${BLOG_DE}_*`,
},
{
selector: 'Politik',
blog: BLOG_DE,
id: `${BLOG_DE}_Politik`,
},
// ... 9 more
];
The screen component is always the same, but must receive the selector and the blog somehow.
Question
How can I change the number of screens, when the the language has changed?
How can I assign the categories to the screen component?
Environment
react-navigation: 1.0.0-beta.11
react-native: 0.45.0
Git-Issue
https://github.com/react-community/react-navigation/issues/1872
I've found a solution and want to share it with you:
You have to recreate the TabNavigator all the time when something has been changed.
For details please look in my Git-Issue and the referenced issue.

How to specify a key for React children when mapping over an array

I have a method in a react Contact List component where I am returning another component. I have got it working but am curious if there is a better way to structure how I am using the key.
Specifically - I'm asking about this line of code from the method below (data is hard coded as sample to get started):
return <ShortContact contact={contact} key={contact.id}/>
Here is the code in context:
_getContacts() {
let contactList = [
{
id: 1,
fName: "aaa",
lName: "aaaaa",
imgUrl: "http://brainstorminonline.com/wp-content/uploads/2011/12/blah.jpg",
email: "aaa#aaaa.com",
phone: "999999999999"
},
{
id: 2,
fName: "bbbbb",
lName: "bbbbbbb",
imgUrl: "https://media.licdn.com/mpr/mpr/shrinknp_200_200/bbb.jpg",
email: "bbb#bbb-bbb.com",
phone: "888888888888"
},
{
id: 3,
fName: "Number",
lName: "Three",
imgUrl: "http://3.bp.blogspot.com/-iYgp2G1mD4o/TssPyGjJ4bI/AAAAAAAAGl0/UoweTTF1-3U/s1600/Number+3+Coloring+Pages+14.gif",
email: "three#ccccc.com",
phone: "333-333-3333"
}
];
return contactList.map((contact) => {
"use strict";
return <ShortContact contact={contact} key={contact.id}/>
});
}
ShortContact Component Render:
class ShortContact extends React.Component {
render() {
return (
<div >
<li className="contact-short well whiteBG">
<img className="contact-short-thumb" src={this.props.contact.imgUrl}/>
<p className="contact-short-name">{this.props.contact.fName}</p><br />
<p className="contact-short-email">{this.props.contact.email}</p>
</li>
</div>
);
}
}
I struggled with how to make it work and not get the warning Warning: Each child in an array or iterator should have a unique "key" prop. However I am wondering if the syntax or structure is valid and if it should be refactored.
There is nothing wrong with this code. The key is required so that react knows how to render the children nodes. In fact your implementation is exactly what react requires the programmer to do. Now the details of which key to use and such can be changed, but it looks like you have the most performant solution already.
The main requirement is that the key is unique so as long as contact.id is always unique (which if its coming from a database then it will be) then you are fine.
Alternatively you can use an index on your map for the key but I wouldn't really recommend it (i'll explain below after the code snippet).
contactList.map((contact, i) => {
return <ShortContact contact={contact} key={i}/>
});
Personally I think your approach is the best approach because it can prevent additional renders. What I mean is for instance when a new contact is returned from the server every contact row would be re-rendered because the index in the array for each contact is different (assuming you aren't treating it like a stack)... The different index with new contact data at that index would cause the re-render. Because contact.id is a static number if the data for that contact hasn't changed then react wont re-render it.
The use of a unique key is required. In your example, using the id is ideal. see the following for more information:
https://facebook.github.io/react/docs/lists-and-keys.html

sencha touch routing extraparams kitchensink

I am trying to extend the routing in the Sencha Touch Kitchensink app as follows:
My data (in List store) are as follows:
{ category: 'fruit', str: 'tomato'},
{ category: 'fruit', str: 'green bean'},
{ category: 'vegetable', str: 'celery'},
{ category: 'vegetable', str: 'sprouts'},
{ category: 'notAVegetable', str: 'ketchup'},
{ category: 'notAVegetable', str: 'prune'}
I would like to show only those data selected by a particular category, such as "fruit"
In the Main.js controller, I am trying to do this by grabbing another parameter from the "List" node in the Demos TreeStore
routes: {
'demo/:id/:category': 'showViewById',
'menu/:id': 'showMenuById'
},
Where the showViewById action adds the extra parameter for use later
showViewById: function (id, category) {
var nav = this.getNav(),
view = nav.getStore().getNodeById(id);
console.log('view ' + id);
this.showView(view);
this.setCurrentDemo(view);
this.hideSheets();
// do stuff with category
},
I am trying to add and access 'category' as an extraParameter in my Demos.js store in the "List" tree node as follows:
{
text: 'List',
leaf: true,
id: 'list',
extraParams: {
category: 'fruit'
}
},
A few questions: Can I use an extraParameter to add this attribute to the Store? If so, how can I access it to use for my routing? I thought it would be available as metadata for my Demos store, but have not been able to access it.
Any alternatives short of creating multiple stores (one for "fruit", "vegetable", "notAVegetable," etc.) with filters on them to achieve the same thing?
TIA!

Resources