NextJS Image component incorrect path - reactjs

I'm working on a NextJS application and I'm having trouble getting the Image component to work.
The normal img element works fine using the same src attribute path as the Image component.
My project has the standard public folder and inside it I have an image called nageldog.png
import Image from "next/image";
...
<img src="/nageldog.png" alt="a"/>
<Image src="/nageldog.png" alt="b" width="64" height="64" />
...
In the browser console
the src path generated for the <img> element looks fine:
<img src="/nageldog.png" alt="a">
the src path generated for the <Image> component looks odd:
<img alt="b" src="/_next/image?url=%2Fnageldog.png&w=256&q=75"
I receive an error in console: "Failed to load resource... status 500" for http://localhost:3000/_next/image?url=%2Fnageldog.png&w=64&q=75
Why won't the Image component load? Thanks!

you can import static images like this
import Image from 'next/image'
import mypic from '../nageldog.png'
const MyImage = (props) => {
return (
<Image src={mypic} alt="Picture of the author" />
)
the problem i have with is when having a lot of images in the public folder

use loader attribute.
<Image src={iconSrc} loader={() => item.iconSrc} alt="Picture of the author" />

Related

React reference local image with absolute path with react

I'm building a simple desktop app using tauri, with a rust backend and a react frontend.
I'm passing the absolute path to a local image (on my device) from the backend to the frontend, and trying to use that path to display the image, but every time, the image isn't loaded and the console looks for the image inside the app folder:
I tried different things but I haven't been able to find a way that works for me to make sure the path given is interpreted as an absolute path, do you have any solution to suggest?
I've just play around and found that ReactJS default doesn't allow us to import any resources outside our app's folder.
As I tried to import an img via an absolute path from C:/ on my device, React returned this error:
Module not found: Error: You attempted to import C:/Users/admin/Pictures/Screenshots/a.png which falls outside of the project src/ directory. Relative imports outside of src/ are not supported.
You can either move it inside src/, or add a symlink to it from project's node_modules/.
So the only way I've found so far is to load the image as a base64 string, there are 2 ways to achieve that:
Import img as a ES6 module
Use <img src={require(...) />
Notice: If you paste your absolute path of the img to browser's address bar then double click it, you can see the "full path" of the img file with the prefix file:///.
Please refer to my example code below:
import React from 'react';
import imgSrc from 'file://C:/Users/admin/Pictures/Screenshots/a.png';
export const Demo = () => {
return (
<div className='test-import-img-from-device'>
<img src={imgSrc} />
It worked
<br /><br />
<img src={require('file://C:/Users/admin/Pictures/Screenshots/a.png')} />
It also worked
<br /><br />
<img src={'C:/Users/admin/Pictures/Screenshots/a.png'} />
Not worked
<br /><br />
<img src={'file://C:/Users/admin/Pictures/Screenshots/a.png'} />
Also not worked
</div>
)
}
Result:
In your case, I think <img src={require('file://...') /> would solve your issue.
Hope this can help!

Can't play audio using React [duplicate]

I have some problem with my images on my react project. Indeed I always thought that relative path into src attribute was built on the files architecture
Here my files architecture:
components
file1.jsx
file2.jsx
file3.jsx
container
img
js
...
However I realized that the path is built on the url. In one of my component (for example into file1.jsx) I have this:
localhost/details/2
<img src="../img/myImage.png" /> -> works
localhost/details/2/id
<img src="../img/myImage.png" /> -> doesn't work, images are not displayed
How is it possible to solve this problem? I want that in any form of routes handled by react-router, all images can be displayed with the same path.
In create-react-app relative paths for images don't seem to work. Instead, you can import an image:
import logo from './logo.png' // relative path to image
class Nav extends Component {
render() {
return (
<img src={logo} alt={"logo"}/>
)
}
}
If you used create-react-app to create your project then your public folder is accessible. So you need to add your image folder inside the public folder.
public/images/
<img src="/images/logo.png" />
You're using a relative url, which is relative to the current url, not the file system. You could resolve this by using absolute urls
<img src ="http://localhost:3000/details/img/myImage.png" />
But that's not great for when you deploy to www.my-domain.bike, or any other site. Better would be to use a url relative to the root directory of the site
<img src="/details/img/myImage.png" />
With create-react-app there is public folder (with index.html...).
If you place your "myImage.png" there, say under img sub-folder, then you can access them through:
<img src={window.location.origin + '/img/myImage.png'} />
If the image is placed inside the 'src' folder, use the following:
<img src={require('../logo.png')} alt="logo" className="brand-logo"/>
Make an images folder inside src(/src/images) And keep your image in it. Then import this image in your component(use your relative path). Like below-
import imageSrc from './images/image-name.jpg';
And then in your component.
<img title="my-img" src={imageSrc} alt="my-img" />
Another way is to keep images in public folder and import them using relative path. For this make an image folder in public folder and keep your image in it. And then in your component use it like below.
<img title="my-img" src='/images/my-image.jpg' alt="my-img" />
Both method work but first one is recommended because its cleaner way and images are handled by webpack during build time.
Some older answers din't work, others are good but won't explain the theme, in summary:
If image is in 'public' directory
Example: \public\charts\a.png
In html:
<img id="imglogo" src="/charts/logo.svg" />
In JavaScript:
Create image to new img, dynamically:
var img1 = document.createElement("img");
img1.src = 'charts/a.png';
Set image to existing img with id as 'img1', dynamically:
document.getElementById('img1').src = 'charts/a.png';
If image is in 'src' directory:
Example: \src\logo.svg
In JavaScript:
import logo from './logo.svg';
img1.src = logo;
In jsx:
<img src={logo} />
I have used it this way and it worked perfectly
import Product from "../../images/product-icon.png";
import { Icon } from "#material-ui/core";
<Icon>
<img src={Product} style={{ width: "21px", height: "24px" }} />
</Icon>
Adding file-loader npm to webpack.config.js per its official usage instruction like so:
config.module.rules.push(
{
test: /\.(png|jpg|gif)$/,
use: [
{
loader: 'file-loader',
options: {}
}
]
}
);
worked for me.
Import Images in your component
import RecentProjectImage_3 from '../../asset/image/recent-projects/latest_news_3.jpg'
And call the image name on image src={RecentProjectImage_3} as a object
<Img src={RecentProjectImage_3} alt="" />
A friend showed me how to do this as follows:
"./" works when the file requesting the image (e.g., "example.js") is on the same level within the folder tree structure as the folder "images".
Place the logo in your public folder under e.g. public/img/logo.png and then refer to the public folder as %PUBLIC_URL%:
<img src="%PUBLIC_URL%/img/logo.png"/>
The use of %PUBLIC_URL% in the above will be replaced with the URL of the public folder during the build. Only files inside the public folder can be referenced from the HTML.
Unlike "/img/logo.png" or "logo.png", "%PUBLIC_URL%/img/logo.png" will work correctly both with client-side routing and a non-root public URL. Learn how to configure a non-root public URL by running npm run build.
If your page url contains multiple / then in src go back / count minus 1 times.
For example page url http://localhost:3000/play/game/ then src url must be ../your-image-folder/image-name. And your your-image-folder must be in public folder.
I create my app with create-react-app and I use require instruction if I want to change dynamically my image src:
export const MyComponent = () => {
const [myImg, setMyImg] = useState(require('./path/to/my/img'));
const handleClick = () => {
setMyImg(require('./path/to/other/img'));
}
return (
<div>
<img src={myImg} alt='myImg' />
<button onClick={handleClick}>Click me!<button/>
<div>
)
}

How to fetch image names from database and display them in react app

The images are stored in the client/public/images folder. And the file name and extension is fetched from a mysql database. How do I write the src attribute of the img element to display the images.
<img src={`%PUBLIC_URL%/images/${portraitFile}`} alt='' />
this is not working
My project structure:
- public
-images
- portrait.jpg
- src
- components
- image viewer component
- App.js
You are using wrong syntax as per CRA app. Use the following:
<img src={require("../images/${portraitFile}").default} alt="" />
Give the path to your images folder.
If the images are in public folder. you can write:
<img src={`../images/${portraitFile}`} alt='Portrait' />
Notice the backticks since you are using template literal syntax.
If your project structure is like this:
- public
- images
- portrait.png
- src
...
- components
...
App.js
and you put your image tag inside App.js, you can source the image like this:
<img src={`../images/portrait.png}`} alt='' />
If you put your image inside your src directory:
- src
- assets
- images
- portrait.png
- components
...
App.js
at the app you can import like this:
import Logo from "./assets/images/logo192.png";
and render using the imported Logo:
<img src={Logo} alt="" />
I've got it guys. It was supposed to be:
<img src={`/images/${portraitFile}`} alt='Portrait' width='70%'/>
since every component is rendered in the index.html file, I should've had made the src structure according to the index.html file. That was it

How should I implement lazy loading for my images in react?

I'm trying to add lazy loading to my react application as I have over 200 images that I don't need on the initial load. If I lazy load the images, does this mean, they won't be loaded until they're needed on the screen?
I'm currently importing 4 groups of about 50 images into .js files and then adding them to objects so they can be dynamically used in my components. It looks like this...
// SportImages.js file
import Football from './images/football.png
import Cricket from './images/cricket.png
import Soccer from './images/soccer.png
... // another 50 or so imports
export default {
Football,
Cricket,
Soccer,
... // another 50 or so files
}
// and then in my component
cards.map(x => {
return (
<img src={SportImages[x.image_ref]} />
)
})
So my question is, should I be using lazy loading in the component file or in the main images file if I want to lazy load every image?
You can add the loading attribute to your image element to lazy-load the images. A complete explainer guide on this attribute can be found on web.dev.
In your case it would probably look as follows:
cards.map(card => (
<img src={SportImages[card.image_ref]} loading="lazy" />
))
You should also make sure to specify the width and height attributes so the browser can place the element on the page with the correct dimensions.
You can use this library called react-lazy-load-image-component
Import the LazyLoadImage component then use it the render you images
cards.map(card => (
<LazyLoadImage src={SportImages[card.image_ref]} {...props}/>
))
You can also add an effect when lazy loading the images. You can check the documentation of the library here
https://www.npmjs.com/package/react-lazy-load-image-component
loading='lazy' attribute Safari not supported
<img loading=lazy src="image.jpg" />
Try this package:
npm i react-lazy-load-image-component
Example:
import React from 'react';
import { LazyLoadImage, trackWindowScroll } from 'react-lazy-load-image-component';
const Gallery = ({ images, scrollPosition }) => (
<div>
{images.map((image) =>
<LazyLoadImage scrollPosition={scrollPosition}
width="100%"
height="auto"
src={image.url} />
)}
</div>
);
export default trackWindowScroll(Gallery);

onError does not load the default image - React

What I am trying to achieve is that a particular image should be loaded for a div, when present. A default image should be loaded for all other divs for whom specific (depending on the name) image is not present.
const defaultImg = require('../images/default.jpg');
But this is the value that console returns for defaultImg - "image /static/media/default.47ce6e77.jpg"
<img src={require(`../images/${imageUrl}.jpg`)} //if I remove ther require form here then the default image is loaded for eveerything, even when the particular image is present.
onError={(event) => event.target.setAttribute("src", {defaultImg})} alt="" />
Instead of the defulat image getting loaded, it throws
Error: Cannot find module './<image-name>.jpg'
I also tried using React Image Fallback
{/* <ReactImageFallback
src={require(`../images/${imageUrl}.jpg`)}
fallbackImage={defaultImg}
initialImage="loader.gif"
alt="A cool image should be here"
className="project-pic"
/> */}
Doesn't work any different.
If const defaultImg = require('../images/default.jpg');
Why does it become /static/media/default.47ce6e77.jpg ?
Check your source in devtool. Your img might be showing as <img src="[object Object]" alt="">.
Replace your onError with onError={(event) => event.target.setAttribute("src", defaultImg)}. You are passing defaultImg as object.
Considerusing the fallback image:
<img src={imagesrc}
onError={(e) => {
e.target.onerror = null
e.target.src = fallbackImg}
} />

Resources