how to display values from 2 arrays in paragraphs in ES6/React - javascript

I am working with bigger arrays in React, and want the following display like this: image/name image/name image/name. I have the following the code but I don't know how I can map over the images array to so it shows it's image. Thank you
function showProtocolsNames() {
if (supportedVaults) {
let arr = supportedVaults
.map((item) => item.protocolName)
.filter((item, index, arr) => {
return arr.indexOf(item) == index;
});
let arrImages = supportedVaults
.map((item) => item.protocolKey)
.filter((item, index, arr) => {
return arr.indexOf(item) == index;
});
let protocolsName = [...new Set(arr)];
let protocolsImages = [...new Set(arrImages)];
console.log(protocolsName, protocolsImages);
return protocolsName.map((vault) => {
return (
<>
{' '}
<img
src={getVaultIcon(vault)}
width="42px"
height="42px"
style={{
marginRight: '12px',
}}
/>
<p className="vaults-protocol">{vault}</p>
</>
);
});
}
return null;
}
Solved: By creating an array of the images and names together and just mapping over it like DBS suggested in comments.

I believe there is a much simpler solution to your problem than your current approach. For example, you could use the supportedVaults data immediately while mapping the image/name components, like this:
function showProtocolsNames() {
// added check to ensure there is data inside supportedVaults
if (supportedVaults.length) {
// removed the two mapped arrays
// added index which is generated by map function
return protocolsName.map((vault, index) => {
// added div instead of <> in order to include a key, which is required in a map function
return (
<div key={`${index}-${vault?.protocolKey}`}>
{" "}
<img
src={getVaultIcon(vault?.protocolKey)} // here we pass protocolKey to the getVaultIcon function
width="42px"
height="42px"
style={{
marginRight: "12px",
}}
/>
{/* here we add protocolName inside the paragraph */}
<p className="vaults-protocol">{vault?.protocolName}</p>
</div>
);
});
}
return null;
}
This logic above is based on your description of the issue, assuming protocolKey is what you need to pass to get the vault icon in getVaultIcon function and protocolName is the value you need to show as the name. If my perception is wrong, please edit your question to reflect more info on what exact data you need to get from the supportedVaults array, or what format supportedVaults has.

Related

What should I use as a key for "row" elements in react?

I have a gallery that displays a number of books per row. This gallery takes an array of books as a prop and uses "itemsPerRow" prop to chunk the books into a 2 dimensional array and then loops through all the books to display the books in a grid-like structure.
export default function Gallery({ items, itemsPerRow, renderLink }) {
itemsPerRow = itemsPerRow ?? 3
const rows = chunk(items, itemsPerRow)
const renderEmptyItems = (itemsToRender) => {
const items = []
for(let n = itemsToRender; n > 0; n--) {
items.push(<GalleryItem key={`empty_${n}`} empty/>)
}
return items
}
return (
<div>
{
rows.map((row, index) => (
<div key={index} className="tile is-ancestor">
{row.map(item => <GalleryItem key={item.id} renderLink={renderLink} {...item}/>)}
{/* Add empty gallery items to make rows even */}
{index + 1 === rows.length && renderEmptyItems(itemsPerRow - row.length)}
</div>
))
}
</div>
)
}
However, unless I give each div representing a row a key, react complains about the lack of keys. As I understand it, using the index as a key doesn't really help react and should be avoided. So what should I use as a key here <div key={index} className="tile is-ancestor"> instead of the index?
Use a unique identifier (book.id, maybe book.title if it's unique) for the key props. If your data does not have a unique identifier, it's okay to use index.
You need to specify a value that uniquely identify the item, such as the id. You can read more about keys in the documentation.
Also it is not recommended to use indexes as keys if the order of your data can change, as React relies on the keys to know which components to re-render, the documentation I linked explains that further.
You can use the unique_identifier which differentiate each of the documents(probably, you should pass the document _id as a key prop in the row components)
<div className="row">
{notes.map((item) => {
return (
<div key={note._id} className="col-md-6">
<Component item={item} />
</div>
);
})}
</div>

Display date in a list conditionally

Currently I'm working on small React project where I'm using data provided by a flight information API. Everything is working according to plan so far. I can display all array items in a list. Now I'm trying to implement a feature that displays date on a separate row in the list. I only want to display a date one time for one or more items with the same date.
Down below in the condition I'm using the variable displayDate. Basically just to be able to turn the date on/off for the moment and to test some logic. What I'm trying to figure now is what logic I need to be able to evaluate the if statement to either true or false. There has to be some sort of comparison between the current date and the next date in the array.
Each object in the array has a property called scheduleDate formatted as "2020-07-06".
Any ideas how I can solve this?
<Flights>
{resolvedData &&
resolvedData.flights
.filter((item) => item.flightName === item.mainFlight)
.map((item, index) => {
if (displayDate) {
return (
<React.Fragment key={item.id}>
<Date date={item.scheduleDate} />
<Flight flight={item} />
</React.Fragment>
);
} else {
return <Flight key={item.id} flight={item} />;
}
})}
</Flights>
Check if the scheduleDate is different than the previous
const renderTable = () => {
let currentDate = null;
return data.map((item, index) => {
if (item.scheduleDate !== currentDate) {
currentDate = item.scheduleDate;
return (
<>
<Date/>
<Flight/>
</>
);
} else {
return <Flight/>;
}
});
};
<Flights>{renderTable()}</Flights>

Display counter prop, when mapping to display component in react.

I have an array, with custom Emoji objects, which I'm mapping through to display in my JSX code.
I have handler, where a user can add an emoji, and will increment a counter, each time it is selected.
addEmoji = (newEmoji) =>{
// mark if new emoji is already in the array or not
let containsNewEmoji = false;
// recreate emojis array
let newEmojis = this.state.emojis.map(emoji => {
// if emoji already there, simply increment count
if (emoji.id === newEmoji.id) {
containsNewEmoji = true;
return {
...newEmoji,
...emoji,
count: emoji.count + 1,
};
}
// otherwise return a copy of previos emoji
return {
...emoji
};
});
I imported the Emoji component, from the emoji-mart node module, and mapping the:
<div className="emoji">
{this.state.emojis &&
this.state.emojis.map( (emoji, index) =>{
return(
<Emoji key={index} onClick={this.addEmoji} tooltip={true}
emoji={{id: emoji.id, skin: 1}} size={25} />
)
})
}
</div>
how can I display the counter variable, next to the Emoji, to see how many times it has been displayed?
You can a create a component called EmojiCount to you'll pass emoji and count as props
const EmojiCount = (props) => {
return (
<Emoji {...props.emoji} />
<div>{props.count}</div>
);
}

Using foreach to select the correct index in an array

I have been having trouble with this problem for a bit now. I use forEach to loop through an array, and I want the correct page to render with the corresponding index when I click on the component. Right now my issue is that I loop through my array, but I am not able to return the correct index, only the first one in the array. I want the startPage prop on the Pages component to render to correct index from my newNum variable.
const itemId = this.props.navigation.getParam('pk');
let newArray = this.props.moment.filter(item => {
return item.trip == itemId
});
console.log('getting moment fromt trip')
let num = Object.keys(this.props.trip[0].moments)
let newNum = num.forEach((number, index) => {
console.log(number)
return number
})
return (
// <View style={{flex:1, backgroundColor: '#F0F5F7'}} {...this.panResponder.panHandlers}>
<View style={{flex:1, backgroundColor: '#F0F5F7'}}>
<HeaderMomentComponent navigation={this.props.navigation} />
<Pages indicatorColor="salmon" startPage={newNum}>
{newArray.map((item, index) => {
console.log('this is the index')
console.log(index)
return(
<MomentContent
name={item.name}
place={item.place}
description={item.description}
tags={item.tags}
key={index}
/>
)
})}
</Pages>
</View>
);
According to MDN documentation (Mozilla Developer Network), return value of forEach is undefined.
Use Array#map to return a newNum value.
let newNum = num.map((number, index) => {
// Some logic to get a new number...
return number
})

How to loop and render elements in React.js without an array of objects to map?

I'm trying to convert a jQuery component to React.js and one of the things I'm having difficulty with is rendering n number of elements based on a for loop.
I understand this is not possible, or recommended and that where an array exists in the model it makes complete sense to use map. That's fine, but what about when you do not have an array? Instead you have numeric value which equates to a given number of elements to render, then what should you do?
Here's my example, I want to prefix a element with an arbitrary number of span tags based on it's hierarchical level. So at level 3, I want 3 span tags before the text element.
In javascript:
for (var i = 0; i < level; i++) {
$el.append('<span class="indent"></span>');
}
$el.append('Some text value');
I can't seem to get this, or anything similar to work in a JSX React.js component. Instead I had to do the following, first building a temp array to the correct length and then looping the array.
React.js
render: function() {
var tmp = [];
for (var i = 0; i < this.props.level; i++) {
tmp.push(i);
}
var indents = tmp.map(function (i) {
return (
<span className='indent'></span>
);
});
return (
...
{indents}
"Some text value"
...
);
}
Surely this can't be the best, or only way to achieve this? What am I missing?
Updated: As of React > 0.16
Render method does not necessarily have to return a single element. An array can also be returned.
var indents = [];
for (var i = 0; i < this.props.level; i++) {
indents.push(<span className='indent' key={i}></span>);
}
return indents;
OR
return this.props.level.map((item, index) => (
<span className="indent" key={index}>
{index}
</span>
));
Docs here explaining about JSX children
OLD:
You can use one loop instead
var indents = [];
for (var i = 0; i < this.props.level; i++) {
indents.push(<span className='indent' key={i}></span>);
}
return (
<div>
{indents}
"Some text value"
</div>
);
You can also use .map and fancy es6
return (
<div>
{this.props.level.map((item, index) => (
<span className='indent' key={index} />
))}
"Some text value"
</div>
);
Also, you have to wrap the return value in a container. I used div in the above example
As the docs say here
Currently, in a component's render, you can only return one node; if you have, say, a list of divs to return, you must wrap your components within a div, span or any other component.
Here is more functional example with some ES6 features:
'use strict';
const React = require('react');
function renderArticles(articles) {
if (articles.length > 0) {
return articles.map((article, index) => (
<Article key={index} article={article} />
));
}
else return [];
}
const Article = ({article}) => {
return (
<article key={article.id}>
<a href={article.link}>{article.title}</a>
<p>{article.description}</p>
</article>
);
};
const Articles = React.createClass({
render() {
const articles = renderArticles(this.props.articles);
return (
<section>
{ articles }
</section>
);
}
});
module.exports = Articles;
Array.from() takes an iterable object to convert to an array and an optional map function. You could create an object with a .length property as follows:
return Array.from({length: this.props.level}, (item, index) =>
<span className="indent" key={index}></span>
);
I'm using Object.keys(chars).map(...) to loop in render
// chars = {a:true, b:false, ..., z:false}
render() {
return (
<div>
{chars && Object.keys(chars).map(function(char, idx) {
return <span key={idx}>{char}</span>;
}.bind(this))}
"Some text value"
</div>
);
}
You can still use map if you can afford to create a makeshift array:
{
new Array(this.props.level).fill(0).map((_, index) => (
<span className='indent' key={index}></span>
))
}
This works because new Array(n).fill(x) creates an array of size n filled with x, which can then aid map.
I think this is the easiest way to loop in react js
<ul>
{yourarray.map((item)=><li>{item}</li>)}
</ul>

Categories