Newbie trying a react.js project. When I try to import an image I get an error message that it failed to compile

Viewed 60

./src/components/Page/Page.js Module not found: Can't resolve './Page/baby.jpeg' in '/Users/kim/Desktop/untitled folder 2/Development/Academy/Projects/portfolio/src/components/Page'

import React, { Component } from 'react';
import './Page.css';
import baby from './Page/baby.jpeg';

class LandingPage extends Component {
    constructor(props) {
        super(props);
        this.state = {};
    }
    render() {
        return (
            <div name='page' className='Page'>
                <h1>Hello,.</h1>
                {/* <hr className='break' */}
                <p>WELCOME</p>
                <img src={baby} width="100" height="50" />
            </div>
        )
    }
}
2 Answers

The problem here is with the image location referencing.

If your folder structure is like this

Page -> LandingPage.js
Page -> Page.css
Page -> baby.jpeg

Then you should import the image like this

import baby from './baby.jpeg';

This should solve your path reference issue because LandingPage component is in the same folder as that of image.

Here is a sample codesandbox with these assumptions

https://codesandbox.io/s/awesome-snowflake-dp8z1?file=/src/App.js

I imagine you've gathered this from the comments, but you need to ensure you have the correct path for "baby.jpeg." It should look in the local directory to find the resource(relative path) unless you specifically give it a global path. Since the "baby.jpeg" is supposed to be in "Page" with your code, perhaps you should try using the path "./baby.jpeg" or change to a global path.

Related