Limit mapped items in a loop [duplicate] - javascript

This question already has answers here:
is there a way to apply map function to a certain array elements reactjs?
(2 answers)
Closed 3 days ago.
I've searched other posts but couldn't quite find I was looking for. I am looping through data from a sanity api but I want to limit it to just the first 4 items returned. What would be the best way to achieve this? Here is the code in question
{mappedPosts && mappedPosts && mappedPosts.map ( (post) => (
<Col className="mapped-posts" style={redLine} xs="12" lg="4">
<div style={imageContainerStyle} onClick={() => router.push(`/logos/${post.slug.current}`)} key={post.index} >
<img
src={post.mainImage}
alt={post.title}
style={imgStyle}
layout="fill" />
<h3 style={titleStyle}>{post.title}</h3>
</div>
</Col>
)) }
Can I do something in the loop like:
{mappedPosts && mappedPosts.length < 4 && mappedPosts.map ( (post) => (
Or is there a better way to control how much data is returned with the map function?

You can take only the first 4 item and loop immediatly after
mappedPost.splice(0, 4).map( (post)=> ....

Related

ForEach inside of a map Javascript React not showing up [duplicate]

This question already has answers here:
How to have nested loops with map in JSX?
(4 answers)
Closed 9 months ago.
Anyone know why this isn't generating any components?
sArray is a 2d array with a structure like a box [[1,2],[4,4]], but it's 5x5
{
sArray.map( (array) => {
console.log('inthemap');
array.forEach(element => {
console.log('intheEach');
return (
<div>
<S ticketValue={element}> </S>
</div>
)
});
})
}
When I run the page the Console logs the InTheMap and then the InTheEach 5 times, and it does this 5 times. Meaning I'm making 25 S components, but they do not show up.
When I remove the forEach, the S component does show up.
There are two issues I see above:
You are missing a return statement for the inner loop
You should be using map instead of forEach since you are returning
{
sArray.map((array) => {
// you forget to return this
return array.map(element => {
return (
<div>
<S ticketValue={element}> </S>
</div>
)
})
})
}
Also quick note that this has a runtime complexity of O(n^2) which may be ok for smaller arrays, but will slow performance exponentially as they grow in size.
You may want to move this from outside the render method and compute with useMemo to prevent unnecessary re-renders:
https://reactjs.org/docs/hooks-reference.html#usememo
// compute this value only once (or add dependencies for when it should update)
const myExpensiveRender = useMemo(() => {
return sArray.map((array) => {
return array.map(element => {
return (
<div>
<S ticketValue={element}> </S>
</div>
)
}
},[])
return (
<>
{myExpensiveRender}
</>
)

How do I properly use the map function to get the index of the element in the array? [duplicate]

This question already has an answer here:
ESCMAScript 6 arrow functions - parentheses around parameter
(1 answer)
Closed 10 months ago.
Hello I am trying to find the index of the element in an array using map so that eventually I can create a onClick function that will change the image based on that index.
However when I add index to my map function I then get an error stating that the img is not defined.
const currentIndex = 0;
const gallery =
product.images.length > 1 ? (
<Grid gap={2} columns={5}>
{product.images.map(img, index => (
<GatsbyImage
image={img.gatsbyImageData}
key={img.id}
alt={product.title}
/>
))}
</Grid>
) : null;
The above code displays a list of thumbnail size images. I would like to eventually be able to click on each image and have the larger image appear.
Code for the larger image is below.
<div>
<GatsbyImage
image={product.images[currentIndex].gatsbyImageData}
alt={product.title}
/>
{gallery}
</div>
Simple parenthesis fix:
const currentIndex = 0;
const gallery =
product.images.length > 1 ? (
<Grid gap={2} columns={5}>
{product.images.map((img, index) => (
<GatsbyImage
image={img.gatsbyImageData}
key={img.id}
alt={product.title}
/>
))}
</Grid>
) : null;
Make sure to not pass two values, but one value to Array.map: a function with its own optional parameter called 'index'
Consider expanding your work to a function that you can just reference, to make life easier, and code more legible, like this:
const currentIndex = 0;
const mapper = (img, index) => (
<GatsbyImage image={img.gatsbyImageData} key={img.id} alt={product.title} />
);
const gallery =
product.images.length > 1 ? (
<Grid gap={2} columns={5}>
{product.images.map(mapper)}
</Grid>
) : null;
See more here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map#syntax

Warning: Each child in a list should have a unique "key" [duplicate]

This question already has answers here:
Understanding unique keys for array children in React.js
(27 answers)
Closed 1 year ago.
{Data.map(datas => <Col lg={4}>
<PriceCard key={datas.id} title={datas.title} text={datas.text} price1={datas.price1} price1text={datas.price1text} price2={datas.price2} price2text={datas.price2text} price3={datas.price3} price3text={datas.price3text} price4={datas.price4} price4text={datas.price4text} price5={datas.price5} price5text={datas.price5text} imgUrl={datas.imgUrl} />
</Col>)}
And I get his error, but I have unique key.
Warning: Each child in a list should have a unique "key"
Col should have a key as well. Try doing this:
{Data.map((datas, index) => <Col lg={4} key={index} >)}

.map not working on array of objects in react [duplicate]

This question already has answers here:
Loop inside React JSX
(84 answers)
When should I use a return statement in ES6 arrow functions
(6 answers)
Closed 2 years ago.
I have the following code:
const displayData = (data) => {
console.log(data);// this shows an array of objects
if (!data.length) return null;
return data.map((movie, index)=>{
<div key={index} className="movie-display" >
<h2>{movie.Title}</h2>
<p>{movie.Year}</p>
</div>
})
}
return (
<div className="search">
<form >
<input
type="text"
placeholder="Enter details here"
onChange={(event) => setSearchTerm(event.target.value)}
/>
<button type="button" onClick={() => fetchData()}>Search</button>
</form>
<div className="movies-list">
{displayData(data)}
</div>
</div>
);
}
And can't get data.map to work
This is what that commented console.log shows in console:
Your syntax is off. You’re not returning anything inside the map function.
You're not returning anything from the map() lambda. You should return the JSX from your map callback as follows:
return data.map((movie, index) => {
return <div key={index} className="movie-display">
<h2>{movie.Title}</h2>
<p>{movie.Year}</p>
</div>;
});

List elements not rendering in React [duplicate]

This question already has answers here:
When should I use a return statement in ES6 arrow functions
(6 answers)
Closed 26 days ago.
This is my Sidebar component.
const Sidebar = React.createClass({
render(){
let props = this.props;
return(
<div className= 'row'>
<h2>All Rooms</h2>
<ul>
{props.rooms.map((room, i) => {
<li key={i}> {room.name} </li>
})}
</ul>
{props.addingRoom && <input ref='add' />}
</div>
);
}
})
This is where I render it populating one room.
ReactDOM.render(<App>
<Sidebar rooms={[ { name: 'First Room'} ]} addingRoom={true} />
</App>, document.getElementById('root'));
The contents inside the <ul></ul> tag don't render at all. Any idea what I could be missing.
You aren't returning anything from the map function, so it renders nothing inside the unordered list. In your arrow function, you do:
(room, i) => {
//statements
}
This doesn't return anything. Array.prototype.map requires a callback that returns a value to do anything. map transform elements to the array, mapping (executing) the callback on each element. The return value is what the value is in the corresponding position in the returned and mapped array.
You must return the list element in the map function like so:
<ul>
{props.rooms.map((room, i) => {
return <li key={i}> {room.name} </li>;
})}
</ul>
Now, the mapped array of list elements is rendered because the list element is returned.
To make this shorter, you may write it in the form (params) => value which is equivalent to the above, where value is the returned value, like so:
{props.room.map((room, i) => <li key={i}> {room.name} </li>)}

Categories

Resources