Images not loading when relative path is used in React - javascript

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="" />

Related

How to set the src attribute in img tag in JSX React? [duplicate]

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';

template literals with import images

<img alt="placeholder" src={ALL.file1.default}></img>
The above works and renders a picture.
I'm trying to use template literals to make the 1 a dynamic variable.
<img alt="placeholder" src={`${ALL.file`${randomnum}`.default}`}></img>
<img alt="placeholder" src={ALL.file`${randomnum}`.default}></img>
Both these don't seem to work as I get an error
Attempted import error: 'file' is not exported from '../images/icons/' (imported as 'ALL').
I imported all the pictures using a index.js in the images folders exporting all of them individually then importing them with:
import * as ALL from "../images/icons/";
Am I using the template literal incorrectly, or does it have something to do with the import conflicting method?
Any help would be appreciated.
Thanks in advance.
Remember when you use dynamic properties you need to use the [] syntax.
In your example, it would go like this:
<img alt="placeholder" src={ALL[`file${randomnum}`].default}></img>

How to set a background image from the public folder in React (Create React App)

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 =)

React Image path is correct but it doesn't find/import it

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]

adding images to in react with dynamic links

I have created react app using create-react-app , there is a component which need to be reused multiple times, this component contain <img> tag, image is different for each instance of the component.
I am passing image path as imagePath prop from parent to child component and then that child need to load image from that path.
i can not use
import image from imagePath
because i don't know the path until component is build, and import statement don't work within component body.
I tried doing<img src={imagePath}>
that also don't work, can you point me to right direction?
adding code for further clarification
first approach it doesnt work. content is object passed by parent and content.image have value of ./images/keeper.PNG
import React from 'react';
import image from './images/keeper.PNG'
export default function Project(props)
{
return <div className='projectContainer' >
<div className='projectImage'>
<img src={props.content.image}
alt ='' />
</div>
<div className='.projectDescription'>
<h4>{props.content.name}</h4>
<p>{props.content.intro}</p>
<h5>Technologies and problems</h5>
<p>{props.content.tech}
</p>
</div>
</div> }
second methond <img src={image} alt ='' /> it works fine and show image but as stated above i don't know image path before the component is created
Sample
Parent component
let image = 'https://www.belightsoft.com/products/imagetricks/img/intro-video-poster#2x.jpg'
function Parent(){
return <Child image={image}/>
}
Child component
function Child(props){
return <img src={props.image} alt="icon-image" />
}
or
directly if you import in component
import imagePath from './image.jpg';
function Child(props){
return <img src={imagePath} alt="icon-image" />
}
Try using it this way, where you can pass the imagePath via props
<img src={require(`${props.imagePath}`)} />
This alone will do the job.
When using Webpack you need to require images in order for Webpack to
process them, which would explain why external images load while
internal do not, so instead of img src= {"/imagePath"} you need to
use img src= {require('/imagePath')} replacing imagePath with the
correct image name for each of them. That way Webpack is able to
process and replace the source img.

Categories