Arduin
Arduin

Reputation: 233

React not Loading Local Images

Recently I've been studying React. I'm facing some issues in my code and don't know the reason.

I'm trying to load a local image in my webpage with the following code:

import React from 'react'
import './style.css'
import Card from '../UI/Card'

const BlogPost = (props) => {
    return (
        <div className="blogPostContainer">
            <Card>
                <div className="blogHeader">
                    <span className="blogCategory">Featured</span>
                    <h1 className="postTitle">Beautiful is Beautiful</h1>
                    <span className="postedBy">Post on 31 of July, by Victor Arduin</span>
                </div>
                <div className="postImageContainer">
                    <img src={require('../../blogPostImages/img1.jpg')} alt="Post Image"/>
                </div>  
            </Card>
            
        </div>
    )
}

export default BlogPost

However, when I access the webpage there is no image. When I check the elements of the page I find the following code:

enter image description here

Somehow, it looks like the image is not being loaded to the page. I have checked many questions in the forum, but none of them seems to explain this problem.

I also tried to reinstall few modules as webpack and other dependencies, but the problem still persists. The tree of files of my project are as following:

enter image description here

Thank you for the support!

Upvotes: 0

Views: 63

Answers (2)

Hitman
Hitman

Reputation: 81

Try importing the image as

import postImage from "../../blogPostImages/img1.jpg";

Modified code


import React from 'react'
import './style.css'
import Card from '../UI/Card'
import postImage from "../../blogPostImages/img1.jpg"

const BlogPost = (props) => {
    return (
        <div className="blogPostContainer">
            <Card>
                <div className="blogHeader">
                    <span className="blogCategory">Featured</span>
                    <h1 className="postTitle">Beautiful is Beautiful</h1>
                    <span className="postedBy">Post on 31 of July, by Victor Arduin</span>
                </div>
                <div className="postImageContainer">
                    <img src={postImage} alt="Post Image"/>
                </div>  
            </Card>
            
        </div>
    )
}

export default BlogPost

Upvotes: 2

elirand5
elirand5

Reputation: 231

import Img1 from '../../blogPostImages/img1.jpg';

<img src={Img1}/>

Upvotes: 0

Related Questions