I've been learning React and practicing with some basic stuff, and this is probably a very simple problem with an even simpler solution, but for the life of me I can't find what i need on google.
Basically i have this piece of code:
export default function BigContainer({ rain, icon, temperature, date }) {
return (
<div className='bigContainer'>
<Container rain={rain[0]} icon={icon[0]} temperature={temperature[0]} date={date[0]} />
<Container rain={rain[1]} icon={icon[1]} temperature={temperature[1]} date={date[1]} />
<Container rain={rain[2]} icon={icon[2]} temperature={temperature[2]} date={date[2]} />
</div>
)
}
The variables in question are simple arrays with either numbers or strings in them, nothing really important.
And I've been looking around for a way to not have to hardcode in the indexation of each property, since hardcoding this stuff isnt ideal.
I've tried mapping one of the arrays but i got kinda confused on how to implement the other properties with relation to the one array i was mapping, so I couldn't get that to work.
So yeah, if theres a way to do like
Loop the stuff here{
<Container rain={rain[i]} icon={icon[i]} temperature={temperature[i]} date={date[i]} />
}
Or something similar, its basically what im looking for. Thank you in advance.
try this you can replace [1,2] with your array you wish to map
[1,2].map((item,index)=>
<Container rain={rain[index]}
icon={icon[index]}
temperature={temperature[index]}
date={date[index]} />
)
This is not the best way to render dynamic values in react. First you need to put the values in an object.
//For example put them in an array called weather and put the values
inside with key-value pairs. Then you can easily loop the values.
export default function App() {
return (
<div className="bigContainer">
{weather.map((value) => (
<table>
<tr>
<th>rain</th>
<th>temperature</th>
<th>date</th>
</tr>
<tr>
<td>{value.rain}</td>
<td>{value.temperature}</td>
<td>{value.date}</td>
</tr>
</table>
))}
</div>
);
}
you can also just pass an array of object instead of passing the array individually since they are related to each other
const weather = [
{
rain: 'rain1',
icon: 'icon1',
temperature: 'temp1',
date: 'date1',
},
{
rain: 'rain2',
icon: 'icon2',
temperature: 'temp2',
date: 'date2',
},
{
rain: 'rain3',
icon: 'icon3',
temperature: 'temp3',
date: 'date3',
},
]
{weather.map((item, key) => (
<div key={key} className='bigContainer'>
<Container rain={item.rain} icon={item.icon} temperature={item.temperature} date={item.date} />
</div>
))}
and map them like this