'How to get Image Url from local Json file in React.js
I want to be able to display images from a local folder by getting the URL from JSON file. So far I've tried :
src={require(blog.imUrl)}
src={blog.imgUrl}
src={require(${blog.imgUrl})}
Errors i am getting when I use require :
Error: Cannot find module '../../images/safe-image.jpeg'
import { useHistory } from 'react-router-dom';
import { Col, Row, Container, Image } from 'react-bootstrap';
import blogArticles from './blog.json';
import './BlogCard.css';
export default function BlogCard() {
const history = useHistory();
function handleClick() {
history.push('/`${blog.id}`');
}
return blogArticles.map((blog) => {
return (
<Container key={blog.id} className="blogContainer">
<Row>
<Col xs={6} md={6} lg={8}>
<h3 className="blogTitle">{blog.title}</h3>
<span className="blogBody">{blog.body.substring(0, 250)}...</span>
<button onClick={handleClick} className="readMoreButton">
Read More
</button>
</Col>
<Col xs={4} md={4} lg={3} className="imageContainer">
<Image src={require(blog.imgUrl)} roundedCircle />
</Col>
</Row>
</Container>
);
});
}```
Here is my JSON File structure :
{
"id": 3,
"title": "abc",
"body": "abcdefg",
"author": "as",
"imgUrl": "../../images/leon-biss.jpg"
}
Solution 1:[1]
I was having this same issue because I had created an image folder inside the src folder and as a result i was unable to display the image. All I had to do to fix this was to:
- move the image folder inside the public folder at the project root folder.
- from the json file, call the image like "/images/productImages/product1.jpeg" .
Hope this solves it for you also.
Solution 2:[2]
Bro, I was working on this problem and eventually figure it out:
1- All you need to do is changing the path of the image from your JSON file. That means the path should be related to your react component (BlogCard).
2- Next thing, instead of using
<MyComponent
image={release.imageURL} // ==> WRONG
/>
Just go with:
<MyComponent
image={`${release.imageURL}`} // ===> CORRECT
/>
Good Luck !!
Solution 3:[3]
Simply react works by rendering jsx so At first always try to maintain javascript or variables before return or render so js works properly in react app . You can try this method and keep your images in public folder. 1.
import { Col, Row, Container, Image } from 'react-bootstrap';
import img from '../path
export default function BlogCard() {
return (
<Image src={img} roundedCircle />
);
});
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 | AWESOME WORLD |
| Solution 2 | Ali Akbar |
| Solution 3 | Kai - Kazuya Ito |
