Advertisements
I am trying to get an image from the database in a table.
The database contains the image name, the images are stored locally in /src/media
The script is in /src/components
For now i am using a mock_data.json file instead of the actual database.
The JSON:
[{"id":1,"Image":"img1.jpg","Cr":"1/2","Name":"Goblin","Source":"Monster
Manual","Type":"Humanoid","Size":"Medium","Alignment":"N","Tag":"tag","Info":"Info"},
{"id":2,"Image":"img2.jpg","Cr":"1/4","Name":"Spider","Source":"Monster
Manual","Type":"Monster","Size":"Medium","Alignment":"N","Tag":"tag","Info":"Info"}
]
The SCRIPT:
import "./Monsters.css";
import data from "./mock_data.json";
import { useState } from "react";
export default function Monsters() {
const [monsters, setMonsters] = useState(data);
return (
<div className="app-container">
<h1>Monsters</h1>
<table>
<thead>
<tr>
<th> </th>
<th>Cr</th>
<th>Name</th>
<th>Source</th>
<th>Type</th>
<th>Size</th>
<th>Alignment</th>
<th>Tag</th>
<th>Info</th>
</tr>
</thead>
<tbody>
{monsters.map((monster) => (
<tr>
<td><img src={`../media/${monster.Image}`} alt={monster.Name} width="25" /></td>
<td>{monster.Cr}</td>
<td>{monster.Name}</td>
<td>{monster.Source}</td>
<td>{monster.Type}</td>
<td>{monster.Size}</td>
<td>{monster.Alignment}</td>
<td>{monster.Tag}</td>
<td>{monster.Info}</td>
</tr>
))}
</tbody>
</table>
</div>
)
};
If I inspect the webpage, I can see the name and location are correct
<img src="../media/img2.jpg" alt="Spider" width="25">
The image is not showing, the alt text is.
What am I doing wrong?
>Solution :
To display images in /src/media
then you can use require()
like so:
<td><img src={require(`../media/${monster.Image}`)} alt={monster.Name} width="25" /></td>
This tells React you’re referencing a local image which is out of the public folder, and it will be included in the build bundle.