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?

2

2 Answers 2

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} />
Sign up to request clarification or add additional context in comments.

Comments

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 (/).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.