Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Jeriah Bowers
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Jeriah Bowers
Front End Web Development Techdegree Graduate 20,590 Points

Images in React.js

Why can't I get local images to load?? I'm using create-react-app and I have the image I'm referring to in the src folder. Here is my app component.

import React, { Component } from 'react';
import './App.css';
import './golf.jpg'

class App extends Component {
  render() {
     return (
       <div className="main">
         <div className="search">
            <input type="text"></input>
            <input type="submit"></input>
         </div>
          <div className="nav">
            <ul>
              <a href="#"><li>Cats</li></a>
              <a href="#"><li>Dogs</li></a>
              <a href="#"><li>Birds</li></a>
            </ul>
          </div>
         <div className="photos">
          <ul>
            <li><img src="./golf.jpg" alt="golf"/></li>
            <li><img src="golf.jpg" alt="golff" /></li>
          </ul>
         </div>
       </div>  
     );
  }
}

export default App;

Any help is appreciated I'm assuming it's something really simple. Thanks.

1 Answer

Ari Misha
Ari Misha
19,323 Points

Hiya there! Lets consider a example:

import React from 'react';
import logo from './logo.png'; // Tell Webpack this JS file uses this image

console.log(logo); // /logo.84287d09.png

function Header() {
  // Import result is the URL of your image
  return <img src={logo} alt="Logo" />;
}

export default Header;

See console.log of logo file only logs out the data uri of the image , not the image itself. This applies to extensions of .jpg, gif, bmp, jpeg and png excluding svg (coz its pretty much HTML). You might ask why does this happen? Since logo, in above example, is the data uri of the image, so yeah when you carry out your build process, webpack or create-react-app couldnt move out the image from the file coz its simply a data-uri , not the image.

But there is an easy fix to this issue. You can place the logo uri in the src attribute of the img tag.

~ Ari