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

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>;
});

Related

Limit mapped items in a loop [duplicate]

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)=> ....

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 can i use argument with '.' operator? [duplicate]

This question already has answers here:
Accessing an object property with a dynamically-computed name
(19 answers)
Closed 1 year ago.
I use React with CSS Module and My code have many repetitive line.
So, I use function to make simple. here is my code.
const SassComponent = () => {
function stylesBox(color) { return `${styles.box} ${styles}.${color}` }
return (
<div className={styles.SassComponent}>
<div className={stylesBox('red')} />
<div className={`${styles.box} ${styles.orange}`} />
<div className={`${styles.box} ${styles.yellow}`} />
<div className={`${styles.box} ${styles.green}`} />
.....
There is my problem when i use 'color' argument with '.'operator. It doesn't work!
How can i fixed it?
Thank you for reading.
Try:
${styles[color]}
instead of
${styles}.${color}

React incrementing variable within .map() function

I am mapping through an array, and I want my variable i to be used as a unique key for my Components, however I do not know how (or where) to increment it correctly, if I add a {i++} within the <Component> tags then it will display the value of i on screen, and if I instead add {this.function(i)} and place the i++ inside the function, it will call the function but the variable i will reinitiate to the value of 0 everytime, so the key value will not be unique. I need the value of i to be the key for the component and it has to be incremented by 1 everytime, does anyone know how I can achieve this? Also, as you can see in the code, when the component is clicked it will make a function call which will send the value of i of the clicked component as a parameter to the called function.
Code:
function(i) {
console.log(i)
}
render() {
var i = 0;
var {array} = this.state;
return (
<div className="App">
{array.map(item => (
<Component key={i} onClick={(e) => this.function(i, e)}>
<p>{item.name}</p>
</Component>
))}
</div>
);
}
The map function gets a second parameter which is the index of the element:
{array.map((item, i) => (
<Component key={i} onClick={(e) => this.function(i, e)}>
<p>{item.name}</p>
</Component>
)}
Be aware that if you intend to sort this array or change its contents at runtime, then using array index as a key can cause some mistakes, as sometimes an old component will be mistake for a new one. If it's just a static array though, then using index as a key shouldn't be a problem.
.map already offer the increment, just add a second variable to the callback
render() {
var {array} = this.state;
return (
<div className="App">
{array.map((item,i) => (
<Component key={i} onClick={(e) => this.function(i, e)}>
<p>{item.name}</p>
</Component>
))}
</div>
);
}
You could try array.map((x, Key) => console.log(key)); ..
In place of console.log you could add your code, it should work fine as per your requirement.

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