I'm new and still learning ReactJS, one issue that's stumping me is trying to use an SVG image I made in Vectornator from my assets folder to a header component in my component folder. It works fine when I made the mockup in HTML and I didn't had this issue when working on an Angular project last semester. Is there a fix or should I switch back to Angular and give up learning React lol. Also I'm using CRA since I just found out there's a lot of other ways to create a React app, chaos for a later date.
I don't know if it has any issue with folder structure because wherever I put the image it gives me this error.
Error Message
This is how my folder structure looks like
Folder Structure
And this is my code. I tried doing this through using an img tag and by making the SVG a react component but nothing works to display the image.
import DVLogo from "../assets/DVLogo.svg";
// import {ReactComponent as DVLogo} from "./assets/DVLogo.svg";
const Header = () => {
return (
<header className="header">
{/* <div>
<DVLogo />
</div> */}
<img src={DVLogo} alt="Logo"/>
<h2 className="header-name">DV</h2>
<nav>
<ul className="nav-links">
<li><a></a>Search</li>
<li><a></a>Collections</li>
<li><a></a>About</li>
<li><a></a>Decks</li>
</ul>
</nav>
<a className="login-btn"><button>Login</button></a>
</header>
);
};
export default Header;
Thanks in advance for any help.
When I use ../ instead of ./
Error #2 part 1
Error #2 part 2
You are not in the correct directory.
When you import your image you need to:
import MyLogo from "../assets/DVLogo.sv" // Note the 2 dots (..)
If you are using the following format:
<img src={DVLogo} alt="Logo"/> // WRONG
You can not pass only DVLogo but also need the src:
<img src={DVLogo.src} alt="Logo"/> // CORRECT
I think it's weird that I'm posting an answer to my own question but maybe it might help someone else or if I forget I can always come back to this.
But what I did was create a component returning the actual SVG code and change the syntax of them to match the JSX.
Examples:
stroke-width to strokeWidth
style="fill-rule: nonzero;" to style={{ fillRule: "nonzero"}}
vectornator:layerName="card" to vectornatorlayername="card"
Below is pics of both for a more in-depth look at the differences if anyone is interested. Thank you guys for helping. Not changing majors yet!
Original SVG file
New SVG component
How can I load image from local directory and include it in reactjs img src tag?
I have an image called one.jpeg inside the same folder as my component and I tried both <img src="one.jpeg" /> and <img src={"one.jpeg"} /> inside my renderfunction but the image does not show up. Also, I do not have access to webpack config file since the project is created with the official create-react-app command line util.
Update: This works if I first import the image with import img from './one.jpeg' and use it inside img src={img}, but I have so many image files to import and therefore, I want to use them in the form, img src={'image_name.jpeg'}.
First of all wrap the src in {}
Then if using Webpack;
Instead of:
<img src={"./logo.jpeg"} />
You may need to use require:
<img src={require('./logo.jpeg')} />
Another option would be to first import the image as such:
import logo from './logo.jpeg'; // with import
or ...
const logo = require('./logo.jpeg'); // with require
then plug it in...
<img src={logo} />
I'd recommend this option especially if you're reusing the image source.
The best way is to import the image first and then use it.
import React, { Component } from 'react';
import logo from '../logo.svg';
export default class Header extends Component {
render() {
return (
<div className="row">
<div className="logo">
<img src={logo} width="100" height="50" />
</div>
</div>
);
}
}
Inside public folder create an assets folder and place image path accordingly.
<img className="img-fluid"
src={`${process.env.PUBLIC_URL}/assets/images/uc-white.png`}
alt="logo"/>
you need to use require and . default
<img src={require('./logo.jpeg').default} />
You need to wrap you image source path within {}
<img src={'path/to/one.jpeg'} />
You need to use require if using webpack
<img src={require('path/to/one.jpeg')} />
put your images in the public folder or make a subfolder in your public folder and put your images there.
for example:
you put "completative-reptile.jpg" in the public folder, then you can access it as
src={'/completative-reptile.jpg'}
you put completative-reptile.jpg at public/static/images, then you can access it as
src={'/static/images/completative-reptile.jpg'}
the best way for import image is...
import React, { Component } from 'react';
// image import
import CartIcon from '../images/CartIcon.png';
class App extends Component {
render() {
return (
<div>
//Call image in source like this
<img src={CartIcon}/>
</div>
);
}
}
const photo = require(`../../uploads/images/${obj.photo}`).default;
...
<img src={photo} alt="user_photo" />
I had the same problem and after research I managed to solve it by putting the JSON data in a constant in JS, with that I was able to import the image and only inform the import in the JSON object. Example:
import imageImport from './image.png';
export const example = [
{
"name": "example",
"image": imageImport
}
]
<Image source={example.image}/>
You have two ways to do it.
First
Import the image on top of the class and then reference it in your <img/> element like this
import React, { Component } from 'react';
import myImg from '../path/myImg.svg';
export default class HelloImage extends Component {
render() {
return <img src={myImg} width="100" height="50" />
}
}
Second
You can directly specify the image path using require('../pathToImh/img') in <img/> element like this
import React, { Component } from 'react';
export default class HelloImage extends Component {
render() {
return <img src={require(../path/myImg.svg)} width="100" height="50" />
}
}
For people who want to use multiple images of course importing them one by one would be a problem. The solution is to move the images folder to the public folder. So if you had an image at public/images/logo.jpg, you could display that image this way:
function Header() {
return (
<div>
<img src="images/logo.jpg" alt="logo"/>
</div>
);
}
Yes, no need to use /public/ in the source.
Read further: https://daveceddia.com/react-image-tag/.
If you dont want to put your image inside public folder use below syntax
src={require("../../assets/images/img_envelope.svg").default}
I found another way to implement this (this is a functional component):
const Image = ({icon}) => {
const Img = require(`./path_to_your_file/${icon}.svg`).ReactComponent;
return <Img />
}
Hope it helps!
First you have to import the image
import logo from './logo.jpeg'; // with import
then plug it in...
<img src={logo} />
That's it.
As some mentioned in the comments, you can put the images in the public folder. This is also explained in the docs of Create-React-App: https://create-react-app.dev/docs/using-the-public-folder/
Step 1 : import MyIcon from './img/icon.png'
step 2 :
<img
src={MyIcon}
style={{width:'100%', height:'100%'}}
/>
For the require method to work, I had to add ".default", like this:
<img src={require('./path/to/image.svg').default} />
I actually just ran into this very same problem and if you move your image file from the ./public directory to the ./src directory you can import or require and either will render.
I have also tested both with the image as well as src attributes in the component and they both worked.
After I tried using the ../ to indicate the exact folder the jpg was located in I was given a usable error that allowed me to make the easy fix.
the computer was kind enough to give me a usable error message.
My answer is basically very similar to that of Rubzen. I use the image as the object value, btw.
Two versions work for me:
{
"name": "Silver Card",
"logo": require('./golden-card.png'),
or
const goldenCard = require('./golden-card.png');
{ "name": "Silver Card",
"logo": goldenCard,
Without wrappers - but that is different application, too.
I have checked also "import" solution and in few cases it works (what is not surprising, that is applied in pattern App.js in React), but not in case as mine above.
I usually prefer to put images in a public folder as recommended in the official documentation.
1. Put your image into public folder. e.g, public/images/image.png
2. use directly into <img>. E.g, <img src="images/image.png" />
As it is in public folder, it will directly use those images. No need to import them.
I have used this way, and it works... I hope you useful.
const logofooter = require('../../project-files/images/logo.png');
return(
<div className="blockquote text-center">
<img src={logofooter} width="100" height="80" />
<div/>
);
import React from "react";
import image from './img/one.jpg';
class Image extends React.Component{
render(){
return(
<img className='profile-image' alt='icon' src={image}/>
);
}
}
export default Image
You could create a file named for instance images.js and reference all your app resources there, later importing that component in all your other component where you would need to display images
I wanted to import multiple images and pass them to different components. It turned out that I need to import multiple images only once and I can use them in any component by passing a prop.
import whiskey from './img/whiskey.jpg';
import hazel from './img/hazel.jpg';
import tubby from './img/tubby.jpg';
Let's make an object.
dog = [
{ name: "Whiskey", src: whiskey },
// ...
]
And display the image
<img src={dog.src}></img>
For me, I wanted to call and use an image within an array block from an image folder. Using the "require" method and concatenating with "default" like this, solved it for me.
in my slide-data.js page:
export const sliderData = [
{
image: require('../../../assets/your-image.jpg').default,
desc: "simple description",
},
You can then use e.g in a separate page, by writing
import { sliderData } from "../../slider-data";
{sliderData.map((slide, index) => {
return (
<div className="" key={index}>
<img src={slide.image} alt="slide" className="image overlay " />
</div>
);
})}
import image from './img/one.jpg';
class Icons extends React.Component{
render(){
return(
<img className='profile-image' alt='icon' src={image}/>
);
}
}
export default Icons;
Well, you all know the answer to the question asked by now, but I am posting this answer to the question which most of you might be wondering after reading other answers:
Question: How the hell am I suppose to import 50 or 100 files:)
Answer: I suggest you make an api (.json) file and in that put the links to all the images and call the api.
That's by far the best way to import files in bulk very easily, although it will take some time and knowledge, which If you don't already know.
An addition, if you have multiple images to import, just and an entry point file, namely a js file the imports all the images and exports them out. Then all you have to do is import all the images from one file.
What I mean is this:
Before app.js
import logo from './logo.png';
import cake from '../assets/cake.jpg';
import image from '../assets/shine.jpg';
src/imageEntry.js
import logo from './logo.png';
import cake from '../assets/cake.jpg';
import image from '../assets/shine.jpg';
export {
logo,
cake,
image
};
After src/app.js
import { cake, logo, image} from './imageEntry.js';
I was importing the images previously like this in React:
import person from '../images/image1.png'
And then using them like this:
<img src={person} alt="" />
Now I want to specify the path in the src itself due to some reason, like this:
<img src="../images/image1.png" alt="" />
But it's not working even though it should.
There are two ways to add images in your JSX with Create React App. The first one is to use import like you did, to import an image that is somewhere in the src folder, like so:
import person from '../images/image1.png'
<img src={person} alt="" />
The second one is to give an image's path to <img>'s src attribute, but it's always relative to the public folder, in a way that the path should starts with /, and / means public folder.
See Adding Images, Fonts, and Files and Using the Public Folder on Create React App's documentation.
For your second attempt to work, you could put images folder inside public folder, and get your images like so:
<img src="/images/image1.png" alt="" />
If your React app will be in a sub folder when deployed, for the second way to work, you should add in your package.json this "homepage":"www.example.com/folder", and use process.env.PUBLIC_URL as below.
<img src={process.env.PUBLIC_URL + "/images/image1.png"} alt="" />
I'm trying to set a background-img in a .css file created in src folde
src/Components/Component/Comp.css
.services {
background-image : url("./images/img-2.jpg");
background-position: center;
background-size : cover;
background-repeat : no-repeat;
color : #fff;
font-size : 100px;
}
I received the following error:
Error: ENOENT: no such file or directory, open 'C:\xampp\htdocs\react\react-website\src\images\img-1.jpg'
For fix it i copied images folder from public to src and it worked fine but now if I want to access those images in that path in a React Component. Ex:
src/Components/Cards/Cards.js
<CardItem
src="./images/img-9.jpg"
text="Explore the hidden waterfall deep inside the Amazon jungle"
label="Adventure"
path="/services"
/>
src/Components/Cards/CardItem.js
const { src, text, label, path } = props
return (
<>
<li className="cards__item">
<Link className="cards__item__link" to={path}>
<figure className="cards__item__pic-wrap" data-category={label}>
<img src={ src } alt="Travel" className="cards__item__img" />
</figure>
<div className="cards__item__info">
<h5 className="cards__item__text">{text}</h5>
</div>
</Link>
</li>
</>
)
I don't receive any error but the image simple doesn't appears.
Where would I keep the images folder and how access to resources from .css and .js files correctly?
If you don't want to import image in your component then you can display image in the following way
var imageName = require('./images/img-9.jpg')
<img src={imageName} />
Here, require used for static "imports", so you need to change your imports.
But you can also do this in the following way
import imageName from './images/img-9.jpg';
<img src={imageName} />
This is another approach to do this
Because your file is located at src/Components/Component/Comp.css and the image is located in the public folder. You will need to go 3 level up from the Comp.css file in order to select the image. You need to do something like this, this will most likely work and your IDE will most likely help you with the path by suggesting it as well:
<CardItem
src="../../../public/images/img-9.jpg"
/>
However, in an ideal scenario, you should not place the images inside the public folder, instead it is better to create an assets folder inside your src and then an images folder within the assets and place your image inside the images folder.
The path in the a case would be:
../../assets/images/img-9.jpg
Here is my solution:
const { src, text, label, path } = props
// How I needed a dinamic solution for reuse the component, here i assign the src value and complete path to a const.
//IMPORTANT: It is an object so we have to access to default property
const imgSrc = require(`../../assets/images/${src}`).default
return (
<>
<li className="cards__item">
<Link className="cards__item__link" to={path}>
<figure className="cards__item__pic-wrap" data-category={label}>
<img src={imgSrc} alt="Travel" className="cards__item__img" />
</figure>
<div className="cards__item__info">
<h5 className="cards__item__text">{text}</h5>
</div>
</Link>
</li>
</>
)
At the end of 2021, this is still an ongoing discussion and a very confusing issue at related repo. (For those who are using up to date version of CRA)
Seems like one single commit was the reason of all these mess (Pretty interesting story actually, you can meet this "famous guy" there in this discussion.) Check out here.
For those who stopped by here because of the same issue and if some other solutions are not working for you, best practice seems like to move all images into src folder. It is not a great solution and not useful in some cases, but still, seems like that's the best option we have so far.
Personally I have created a folder under src as : src/assets/images
And moved all my images there. In JSX files, to be able to use any image in this folder, we need to import it first like so (The path of yours may vary) :
import deleteModalIcon from '../../../assets/images/delete_modal_icon.svg'
Then, I could use it like so :
<img src={deleteModalIcon} alt='' />
In my css file which is located at top level of src folder, to be able to use an image, I did this :
.name:after {content: url('assets/images/edit_icon.svg');}
Please note that there are some complains there in this discussion about disappearing images after the build.
For people who will be reading this in the future: if there is a solid solution or an official fix for that issue at your time, please let me know in comments =)
I have images in one folder while one of the images is getting imported easily the second one isn't being found
import img from '../Img/a292.jpg';
// import img from '../Img/building5.png';
export default function First() {
return (
<section id="first" className="d-flex justify-content-center align-items-center">
<img src={img} alt="img"/>
</section>
)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
My screen
when importing building5.png
when importing a292.jpg
EDIT: Things I have tried src={require('../Img/a292.jpg')} and I have tried to convert the image to png because all the PNG-s were working so I thought it's the format that meters,but no didn't work :/
I have an exotic solution, It's happening very rarely but it might happen to you, Change the name to numbers like 123.jpg
It might happen that the letter a is in Russian and English or something like that, just try
Well, I've faced the same issue and I do the following to import images:
Place the image a292.jpg in Public folder.
Now you can directly write in the img src the path as './a292.jpg'. [The path is relative to the Public folder because index.html is present in public folder so when the virtual DOM is rendered it takes the relative path from index.html]