This question already has answers here:
I can't reference an image in Next.js
(8 answers)
Closed 12 months ago.
am trying to insert an image in my main component everything is working fine, my alt atribute is displaying but the image in not displaying on the browser. please what am i doing wrong
import port from "../public/port.png";
export default function Main() {
return (
<section className="">
<div className="">
<img src={port} alt="illustration" />
</div>
</section>
);
}
if your file exist in public folder, then you dont have to import it. it is accessible globally.
export default function Main() {
return (
<section className="">
<div className="">
<img src="/port.png" alt="illustration" />
</div>
</section>
);
}
Use image tag
<img src="/public/port.png" alt="your alt">
next/image has been introduced since v.10.0.0. You can use either
Statically imported
import port from "../public/port.png";
<Image
src={port}
alt="your alt"
// width={500} automatically provided
// height={500} automatically provided
// blurDataURL="data:..." automatically provided
// placeholder="blur" // Optional blur-up while loading
/>
Path string (internal URL | external URL)
// Example external source
module.exports = {
images: {
domains: ['example.com'],
},
}
<Image
src="https://example.com/image1.png"
// ...
/>
Related
import logo from './logo.svg';
import './App.css';
import img1 from './images/download.png'
> function image( ){
> return (
> <img src={(img1)}/>
> )
> }
function App() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Edit <code>src/App.js</code> and save to reload.
Welcome to your first website!
</p>
<Link value='Learn React!'/>
<Link value='Another link!'/>
</header>
image();
</div>
);
}
I've tried different ways of importing the image but none of them seem to not give me errors. I'm still a beginner and just need to find a resolve to this. I apologize if this is a simple question
Your function needs to be in brackets:
...
</header>
{image()}
...
You can also just put the image url/path in the element.
src="./images/download.png"
or if you're looking for it to be more dynamic, assign the url/path to a variable and pass it into your function. OR just include the img element in your return html.
function image(src){
return (
<img src={src}/>
)
}
OR
...
</header>
<img src="./images/download.png" />
</div>
You can also, while assigning it to a variable, keep it dynamic by passing in the source down to the return html:
...
const src = './images/download.png'
return (
...
</header>
<img src={src} />
</div>
...
Could you explain further what errors you are getting?
:I have the following problem with a Nuxt3 application.
When set an image source via template strings the build process will not render the images.
Otherwise it will, when i set the image src normally. But i need it dynamically.
There are teasers with different images that need to be rendered.
Everythung is working fine, e.g. props ...
The working code:
...
<img
src="/assets/_DSC0238_E.jpg"
:alt="props.name"
class="w-full aspect-square object-cover"
:class="`aspect-${props.aspectRatio}`"
/>
...
The not working code:
...
<img
:src="`props.image`"
:alt="props.name"
class="w-full aspect-square object-cover"
:class="`aspect-${props.aspectRatio}`"
/>
...
What is the way to solve this issue?
In case you are using Nuxt 3 with Vite as Bundler
Set Assets composable.
export default function useAssets() {
const svgs = import.meta.globEager('/src/assets/*.svg');
const pngs = import.meta.globEager('/src/assets/*.png');
const jpegs = import.meta.globEager('/src/assets/*.jpeg');
return {
aboutImage: svgs['/src/assets/aboutImage.svg'].default,
search: svgs['/src/assets/search.svg'].default,
info: pngs['/src/assets/info.png'].default,
};
}
Then in any file:
<template>
<div>
<img :src="assets.info">
</div>
</template>
<script lang="ts">
import { defineComponent } from '#vue/runtime-core';
import useAssets from '../composable/useAssets';
export default defineComponent({
setup() {
const assets = useAssets();
return {
assets,
};
},
});
</script>
resource
In case (Vu3, Vue2, Nuxt 2) and bundler is Webpack
You need to require the image path, and set a dynamic src attribute by adding a colon before :src
<img
:src="require(`~/assets/${props.image}`)"
:alt="props.name"
class="w-full aspect-square object-cover"
:class="`aspect-${props.aspectRatio}`"
/>
In case (Vu3, Vue2, Nuxt 2) and bundler is Vite
const getImage = async imgName => {
// set the relative path to assets
const module = await import(/* #vite-ignore */ `../../assets/${imagName}`)
return module.default.replace(/^\/#fs/, '')
}
<img
:src="getImage(props.image)"
:alt="props.name"
class="w-full aspect-square object-cover"
:class="`aspect-${props.aspectRatio}`"
/>
we can use v-bind to assign them a string value dynamically. read this
Try like this:
<img
v-bind:src="require(`#/assets/${props.image}`)"
:alt="props.name"
class="w-full aspect-square object-cover"
:class="`aspect-${props.aspectRatio}`"
/>
or for shorthand syntax
<img
:src="require(`#/assets/${props.image}`)"
:alt="props.name"
class="w-full aspect-square object-cover"
:class="`aspect-${props.aspectRatio}`"
/>
I don't understand why I cannot see my image, I mean I just see the alt attribute instead of the picture. Here is my code :
import React, {Component} from "react";
const Cards = (props) => {
return (
<>
<div id="card" className={"card text-white bg-" + props.bootstrap + " mb-3"}
style={{maxWidth: 200, marginRight: 10}}>
<div className="card-header">Test</div>
<div className="card-body">
<img src="test.jpg" width="200px" height="200px" className="card-img-top" alt="test" />
<h4 className="card-title">Description</h4>
</div>
</div>
</>
)
}
export default Cards;
whereas when I try this modification it works :
import React, {Component} from "react";
import logo from './test.jpg';
const Cards = (props) => {
return (
<>
<div id="card" className={"card text-white bg-" + props.bootstrap + " mb-3"}
style={{maxWidth: 200, marginRight: 10}}>
<div className="card-header">Test</div>
<div className="card-body">
<img src={logo} width="200px" height="200px" className="card-img-top" alt="test" />
<h4 className="card-title">Description</h4>
</div>
</div>
</>
)
}
I don't understand why this does not work. For me the path is good.
Could you help me please ?
Thank you a lot !
alt will be presented each time the image would not load properly.
So in your case, the latter example would work properly because logo is actually pointing to the jpg image, and the image could be displayed without the alt string.
The first example you shared would not work because src doesn't have an actual pat, it only has a string that isn't resolved into an image hence no image would be loaded and the browser will present the alt value.
on most occasions, images (static files) should be stored in your /public folder.
You can create a images folder in your public folder and then you set src="/images/test.jpg" instead of just "test.jpg"
You need to import
In some case if still not work
than check config file as I described
Note: need to install file-loader package
import React, {Component} from "react";
import logo from './test.jpg';
const Cards = (props) => {
return (
<>
<div id="card" className={"card text-white bg-" + props.bootstrap + " mb-3"}
style={{maxWidth: 200, marginRight: 10}}>
<div className="card-header">Test</div>
<div className="card-body">
<img src={logo} width="200px" height="200px" className="card-img-top" alt="test" />
<h4 className="card-title">Description</h4>
</div>
</div>
</>
)
}
In Config file:: MAKE SURE FOLLOWING RULES DEFINED
module.exports = {
// other config
module: {
rules: [
// other rules
{
test: /\.(png|jpg|gif|svg)$/,
loader: 'file-loader'
},
]
}
}```
Try like this:
<img src="./test.jpg" ...
It should work, if the picture is in the public folder.
The answer is : <img src={require('./test.png').default} />
That's because webpack is configured to bundle your images and assets by using the JSX syntax. Anything within {} can be seen as a property of a component. When it's inside the src attribute it becomes a property of the src and webpack than knows what to do. If you are simply adding the string it will view the source as a string rather than an image.
The path alone will only have meaning when you convert it from a meaningless string to an object. An alternative to your first approach could be
<img src={require('/text.jpg')} />
That should work too.
I am trying to display a pic inside a card but it does not work... actually I only see instead of the pic the attribute alt but I don't see the pic...
Here is my code :
import React, {Component} from "react";
import classes from "./cards.css"
const Cards = (props) => {
return (
<>
<div id="card" className={"card text-white bg-info mb-3"}
style={{maxWidth: 200, marginRight: 10}}>
<div className="card-header">Test</div>
<img src="myPicture.jpg" className="card-img-top" alt="pic" />
<div className="card-body">
<h4 className="card-title">This is a test</h4>
</div>
</div>
</>
)
}
export default Cards;
Do you know how can I do to see my pic on my card ?
Thank you a lot for your help !
Have you checked that the image has loaded correctly? You can use the inspector 'network' tab. Make sure the image is being loaded by the page. It will likely be red if it is not found (in the inspector).
If you're using webpack, try this:
import backgroundImage from './myPicture.jpg';
// all other code
return (
<div>
<img src={backgroundImage} alt="Background image" className="image" />
</div>
)
Config required in webpack:
module.exports = {
// other config
module: {
rules: [
// other rules
{
test: /\.(png|jpg|gif|svg)$/,
loader: 'file-loader'
},
]
}
}
You need to install file-loader package
Add this
import BackgroundImage from './myPicture.jpg';
<img src="{require('./myPicture.jpg')}" className="card-img-top"alt="pic" />
so I am trying to use an if statement but don't know how to word it properly, or if I can with React in a jsx file. My goal is to select the image based on the first name attribute I chose and worked so here is the code for the App.js I am trying to keep it as simple and basic as possible so I can try to figure out a nice clean way to do it but I have no clue. Thanks :)
import './App.css';
import PersonalCard from './components/personal.jsx'
function App() {
return (
<div className="App">
<PersonalCard firstName="Lou" lastName="Ferrigno" age={68} hairColor="Black" />
<PersonalCard firstName="Arnold " lastName="Schwarzenegger " age={73} hairColor="Brown" />
{/* Franco died in 2019 at the age of 78 :'( */}
<PersonalCard firstName="Franco" lastName="Columbu " age={79} hairColor="Brown" />
<PersonalCard firstName="Frank " lastName="Zane " age={78} hairColor="Black" />
</div>
);
}
export default App;
now here is the code for the jsx file
import React from 'react';
const theW ={
width:'400px',
}
const PersonCard = props => {
const {lastName,firstName,age,hairColor} = props
return(
<div className="card" style={theW}>
<img className="card-img-top" src="" alt="Card image"></img>
<section className="card-body">
<h1 className="card-title">{ lastName }, { firstName }</h1>
<p className="card-text">Age: { age }</p>
<p className="card-text">Hair Color: { hairColor }</p>
See Profile
</section>
</div>
);
}
export default PersonCard;
you just need to add the src attribute of the image as dynamic.
so in your code
div className="card" style={theW}>
<img className="card-img-top" src={`location/${firstname}.jpg`} alt="Card image"></img>
here location is the path to the file
EDIT
webpack require additional files to be imported so
<img className="card-img-top" src=require({`location/${firstname}.jpg`}) alt="Card image" />
Thank you so much for trying # Sharun K K but even though it might have been something I was doing wrong that require way did not work for me.
What I did to fix this and shout out to this video on youtube Esterling Accime!,was instead I added an image folder in the public section and did this line of code
<img className="card-img-top" src={`/images/${firstName}.jpg`} />
so that worked wonders for me once again thank you so much for the help :). Another issue with this was I put a name in the App.js file I did this
// this is wrong because of the space in the firstName
<PersonalCard firstName="Lou " lastName="Ferrigno" age={68} hairColor="Black" />
// so no spaces like this
<PersonalCard firstName="Lou" lastName="Ferrigno" age={68} hairColor="Black" />
// and all my issues went away.