How to get Image Url from local Json file in React.js

て烟熏妆下的殇ゞ 提交于 2021-02-18 18:01:06

问题


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"
}


回答1:


You can use this for importing and showing an image which is on src folder (next to javascript files):

import img from "./img1.png";
const imgComponent = () => <img src={img} />

But since you want to load images from json file dynamically, you should put your images inside a folder like images in public folder (public/images/img1.png), then you can render it with:

<img src="/images/img1.png" />
  • Note1: note that currently your json file contains the pathes relative to script file, but you should change it to the path of image in public folder instead. (if you can't change the json file, you can map that url with code also.)
  • Note2: i assumed that you are using creat-react-app which it has public folder by default. if you don't have it, search for how to serve static files in react.


来源:https://stackoverflow.com/questions/63253484/how-to-get-image-url-from-local-json-file-in-react-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!