Oops, good old Allan?
Edit: I almost forgot to mention which link I was inspired to answer. Follow:
https://medium.com/javascript-in-plain-english/how-to-loop-through-arrays-in-react-3eaa8a14445
On the map, come on:
There is no magic formula for an iteration. It has to be developed according to your need, you know?
I created an example here for you. Let’s debug:
import React from 'react';
import EasyMap from './components/EasyMap';
import './App.css';
function App() {
return (
<div className="App">
<EasyMap />
</div>
);
}
export default App;
I put up an example of an App, importing the component that will iterate.
But the secret is in the next code:
import React from 'react';
const resposta = [
{ id: 35, item: 'jumper', color: 'red', size: 'medium', price: 20 },
{ id: 42, item: 'shirt', color: 'blue', size: 'medium', price: 15 },
{ id: 71, item: 'socks', color: 'black', size: 'all', price: 5 },
];
class EasyMap extends React.Component {
constructor(props) {
super(props);
this.state = {
lista: [],
};
}
componentDidMount() {
this.setNewData();
}
setNewData() {
this.setState({
lista: resposta,
});
}
mapReturn(callback) {
return callback.map(value => {
return (
<div key={value.id}>
<h2>{`Product: ${value.item}`}</h2>
<p>{`Color: ${value.color}`}</p>
<p>{`Size: ${value.size}`}</p>
<p>{`Price: $${value.price}`}</p>
</div>
);
})
}
render() {
return (
<div>{this.mapReturn(this.state.lista)}</div>
);
}
}
export default EasyMap;
- I created a component called "Easymap" that receives a constructor to treat the state, and in state I created a key (which was the key you asked for).
- I called in Componentdidmount(which is a function that is part of React lifecicle, where it performs this function as soon as the component is mounted) a function that modifies the state value for an array, which I created above the component.
- I created a function (mapReturn) that creates a div for each object inside the array, where it is passed to this div a key(Required for React to better manage its components), and in this div several tags were passed
with access to the values of each object in this array. That is: Each object receives a div, receiving its Key and its properties/values.
- This function is rendered inside the component’s Return, inside a , as it is necessary for React to receive a parent in this function.
Put a bullet in it. Tmj!
I don’t understand the question!
– sant0will
That’s the way to do it...
– Emerson Vieira
No foot, no head, no body!
– novic
This is a comment that many people come to me, I put here exactly to minimize the doubt of the crowd, IE is another vent
– Allan Monteiro
Stackoverflow is not a forum to vent
– sant0will
How to ask?
– sant0will