Reputation: 509
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.
Upvotes: 0
Views: 3593
Reputation: 145
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;
Upvotes: 0
Reputation: 26909
If you are using Create React App, the process is fairly easy and straight-forward.
Are you import
ing it or doing something like <img src="../whatever/>
? You need to be import
ing 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.
Upvotes: 1