0

I have sampleposition.png in my assets folder, and a page called myPage.js in my components folder. How do I reference the sampleposition.png in my assets folder from myPage.js. I've tried src="../assets/sampleposition.png" / but that doesn't seem to be working.

enter image description here

Jon
  • 501
  • 3
  • 18
  • The idiomatic way to achieve what you want is to use a bundler (such as webpack) and a "compiler" (such as babeljs), and instead use an `import` statement so you can use the image as a component. https://stackoverflow.com/questions/66410782/how-to-load-image-react-babel – Alan Sep 08 '21 at 16:39
  • https://stackoverflow.com/questions/37644265/correct-path-for-img-on-react-js – CuteShaun Sep 08 '21 at 16:40

2 Answers2

1

If you are using Create React App, the process is fairly easy and straight-forward.

Are you importing it or doing something like <img src="../whatever/>? You need to be importing so that the build will know how to access it at runtime. See Adding Images, Fonts, and Files

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;

If you aren't, you need to be serving the content statically and referencing the static content address or use a build/bundle tool to put the content into a place that is known ahead of time which is what the create-react-app tool sets up for you.

zero298
  • 25,467
  • 10
  • 75
  • 100
0

Import your image and use it in the code. This should do it according to your requirement.

import React from 'react';
import myImage from '../assets/sampleposition.png'; 



function YourFunction() {
  
  return 
        <img src={myImage} alt="myImage" />;
}

export default YourFunction;
bad_coder
  • 11,289
  • 20
  • 44
  • 72
Shehan Silva
  • 105
  • 6