Reputation: 1222
I'm trying to generate a soccer points table in React from an array of images. For instance this is my array:
import arsenal from './images/Arsenal.png';
import bournemouth from './images/AFCBournemouth.png';
import villa from './images/AstonVilla.png';
const icons =[{arsenal},{bournemouth},{villa}];
At the moment my class is created like this:
class Standings extends React.Component{
render(){
return(
<Table striped bordered hover size="sm">
<thead>
<tr>
<th>Teams</th>
<th>Points</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<img src={bournemouth} class="icon" height="42" width="42" />
</td>
<td>0</td>
</tr>
<tr>
<td>
<img src={arsenal} class="icon" height="42" width="42" />
</td>
<td>0</td>
</tr>
<tr>
<td>
<img src={villa} class="icon" height="42" width="42" />
</td>
<td>3</td>
</tr>
</tbody>
</Table>
)
}
}
Is there a way to generate the table by looping through the image array? I'd like to add more images to the array if possible.
Upvotes: 0
Views: 857
Reputation: 15146
Use map()
The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.
const icons =[arsenal, bournemouth, villa];
class Standings extends React.Component {
render() {
return (
<Table striped bordered hover size="sm">
<thead>
<tr>
<th>Teams</th>
<th>Points</th>
</tr>
</thead>
<tbody>
{icons.map((url, idx) => (
<tr>
<td>
<img src={url} class="icon" height="42" width="42" />
</td>
<td>{idx}</td>
</tr>
))}
</tbody>
</Table>
);
}
}
Upvotes: 1
Reputation: 1805
You can create an array of objects with the teams:
const teams = [
{
url: 'url',
name: 'Arsenal,
points: 3
}
]
Then iterate over it:
<Table striped bordered hover size="sm">
<thead>
<tr>
<th>Teams</th>
<th>Points</th>
</tr>
</thead>
<tbody>
{
teams.map((team) => (
<tr>
<td>
<img src={team.url} class="icon" height="42" width="42" />
</td>
<td>{ team.points }</td>
</tr>
}
</tbody>
</Table>
Also, if that does not work try to set the src of img like this:
<img src={{uri: team.url}} />
Upvotes: 0