简体   繁体   中英

broken logo image when importing from json file in React App

I am in the process of importing an svg image which path is in a json file. Below is part of the json file:

[
{
  "id": 1,
  "company": "Photosnap",
  "logo": "./images/photosnap.svg",
  "new": true,
  "featured": true,
  "position": "Senior Frontend Developer",
  "role": "Frontend",
  "level": "Senior",
  "postedAt": "1d ago",
  "contract": "Full Time",
  "location": "USA Only",
  "languages": ["HTML", "CSS", "JavaScript"]
},
{

I have created two components. As the app is showing a list of jobs. So the I have a job list component and a job card component. The code for the job listing component is as follows:

import React from 'react';

import './job-listing.styles.css';
import JobCard from '../job-card/job-card.component.jsx/job-card.component';
import { Component } from 'react';


class JobListing extends Component {
constructor() {
    super();
    this.state = {
        jobs: []
    }
   };

   componentDidMount() {
    fetch('/data.json')
    .then(response => response.json())
    .then(data => this.setState({jobs: data}))

}
render() {
    return (
        <div>
            {this.state.jobs.map(({id, ...otherJobProps}) =>(
            <JobCard key={id} {...otherJobProps} />
            ))}
        </div>

       )
     }
   }

  export default JobListing;

and for the Job Card component is below:

import React from 'react';

import './job-card.styles.css';

const JobCard = ({company, position, postedAt, contract, location, logo }) => (
<div className='card'>
<img src={logo} alt="logo" width="42" height="42"></img>
<h2>{company}</h2>
<h1>{position}</h1>
<div className='details'>
    <h3>{postedAt} &#183;</h3>
    <h3>{contract} &#183;</h3>
    <h3>{location}</h3>
 </div>
</div>
)

export default JobCard; At the moment this is what I get破碎的形象

Any help would be appreciated.

If you are using create-react-app you will want to put static assets such as images (if you are not not ES6 import ing images into the code) in the public folder . Try moving these images into the public folder created by create-react-app . You may also need to update the paths. Assuming your structure is:

public
  images
    photosnap.svg

You may need to change:

"logo": "./images/photosnap.svg",

to:

"logo": "/images/photosnap.svg",

Hopefully that helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM