'Images are disappearing after refreshing the page in React
I am trying to display the data and image using a component.First time the data and images appears but when i refresh the page then data and images both disappear.
This is by component Team.js
import React from 'react';
const Team = (props)=>{
return(
<>
<h1>{props.data.name}</h1>
<img name="photo" src={require(`../images/${props.data.image}`)}/>
</>
)
}
export default Team;
My component is present in components folder and images are present in images folder.
Solution 1:[1]
require usually does not work with string literals (template strings). In other words, the location needs to be known at compile time.
I see two solutions.
1. Store your images in the public/images folder, and reference them using your website URL (Preferable)
Lets say you store all your image in the public/images folder. We can get the public url of the website using
var imageBasePath = window.location.protocol + "//" + window.location.host + "/images/";
this will then allow us to use this to reference our public images in the src for an img tag.
<img name="photo" src={imageBasePath + props.data.image} />
where image is the actual name of the image located in the public/images folder.
your team component would look like this
const Team = (props) => {
var imageBasePath =
window.location.protocol + "//" + window.location.host + "/images/";
return (
<>
<h1>{props.data.name}</h1>
<img name="photo" src={imageBasePath + props.data.image} />
</>
);
};
2. Store required images in an array and reference by index, export as an object.
Probably not the preferable method, as working with indexes can be tricky.
export const imageList = [
require("./checklist.jpg"),
require("./question.jpg"),
require("./test-pattern.jpg")
];
and then the Team implementation
import { imageList } from "./Images/imageList";
export const TeamRequire = (props) => {
let image = imageList[props.data.id];
return (
<>
<h1>{props.data.name}</h1>
<img name="photo" src={image} />
</>
);
};
to ease the index issue, we can store and fetch them by objectKey instead
export const imageListObj = {
checkList: require("./checklist.jpg"),
question: require("./question.jpg"),
testPattern: require("./test-pattern.jpg")
};
import { imageListObj } from "./Images/imageList";
export const TeamRequireObj = (props) => {
let image = imageListObj[props.data.imageId];
return (
<>
<h1>{props.data.name}</h1>
<img name="photo" src={image} />
</>
);
};
Here is a codesandbox with the three concepts.
https://codesandbox.io/s/adoring-rosalind-2xhj67?file=/src/App.js
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
