1

I am trying to set the path of an Image inside a img tag in ReactJS but It is not showing...

This is what I tried...

import React, { Component } from "react";
import { Carousel } from "react-responsive-carousel";
import "react-responsive-carousel/lib/styles/carousel.css";

export default class CarouselComponent extends Component {

  render() {
    return (
      <Carousel
        showArrows
        emulateTouch
        infiniteLoop
        autoPlay
        interval={2000}
        onChange={this._onChange}
        onClickItem={this._onClickItem}
        onThumbClick={this._onClickThumb}
      >
        <div>
    <img src="../images/sample1.jpg" /> {/*not working*/}
          <p className="legend">Welcome to W.W Coders</p>
        </div>
        <div>
          <img src="http://placehold.it/1080x300?" />
          <p className="legend">Faculty of Computing</p>
        </div>
        <div>
          <img src="http://placehold.it/1080x300?" />
          <p className="legend">Faculty of Engineering</p>
        </div>
        <div>
          <img src="http://placehold.it/1080x300?" />
          <p className="legend">Faculty of Business Management</p>
        </div>
      </Carousel>
    );
  }
}

And this is my folder structure

folder structure

Can someone tell me where I have went wrong?

Jananath Banuka
  • 2,951
  • 8
  • 57
  • 105
  • 2
    Possible duplicate of [How do I reference a local image in React?](https://stackoverflow.com/questions/39999367/how-do-i-reference-a-local-image-in-react) – yiksanchan Jun 18 '19 at 19:55
  • Possible duplicate of [React won't load local images](https://stackoverflow.com/questions/34582405/react-wont-load-local-images) – Emile Bergeron Jun 18 '19 at 20:06

2 Answers2

1

From your project structure, it looks like the public folder is where you should put all your images. Any files that are accessible by url directly (like images), should be inside this folder. The files inside src and other folders are intended to be built/compiled and not directly accessed via a URL.

You should move your images folder to be inside the public folder. So it would be like:

/public/images/sample1.jpg

Then you would access it like:

src="/images/sample1.jpg"

Assuming you are using create-react-app here's some info about the public folder. It looks like they want you to use a variable for the path, but often you can just use the root (/).

Austin Greco
  • 32,997
  • 6
  • 55
  • 59
1

Assuming you are using webpack or a similar bundler for your code compilation, you can use the file-loader to ensure that the image is copied to the compile folder, and you get the path pointing to it as such:

import imagePath from '../images/sample.jpg'

...

<img src={imagePath} />
Dmitri Farkov
  • 9,133
  • 1
  • 29
  • 45