Using an imported image based on json data character name - javascript

I am getting data from a json file and when I get the character name of the object i'd like the div to render an image from an image I had imported. But when I use src={char} and say for example the char from the json file is 'sage' i'd like to use the sage image. But doing this method does not work like that. Also I am successfully getting the data from the json file so no problems on that end.
Thanks!
import sage from '../../assets/images/agents/sage_thumb.webp';
import viper from '../../assets/images/agents/viper_thumb.webp';
import jett from '../../assets/images/agents/jett_thumb.webp';
import valorant_rank from '../../assets/images/ranks/valorant.png';
const renderBody = () => {
return matchData && matchData.map(({ id, char, name, roundsPlayed, performance, multiKills, team }) => {
return (
<tr key={id} className='tr-background'>
<td className='match-table__agent-cell'><img className='img-fluid' src={char} alt="" /></td>
</tr>
)
})
}

I would use an object to map the agent name to its image url
const imageByAgent = {
sage: "../../assets/images/agents/sage_thumb.webp",
viper: "../../assets/images/agents/viper_thumb.webp",
...
}
And for the image src you can fetch the url using the character name
<img className='img-fluid' src={imageByAgent[char]} alt="" />

Related

Unable to display image with dynamic path using Reactjs

I am working on Reactjs and i am using nextjs framework,Right now i am trying to fetch image data from database using axios,I am using loop for fetch image,Image in database is
like "http://xxxxxxxxxxxxxxxx/upload/blog/1669111567istockphoto-1354441996-170667a.jpg" means
i am getting full path of image,But whenever i am trying to fetch data then i am getting following
error
Error: Invalid src prop ...on `next/image`, hostname "diggdevelopment.com" is not configured under images in your `next.config.js`
Also i want if array(todoList) is not empty then loop should work(add condition if array not empty) and want to show number of records ( like 1 2 3 etc..)
I tried with following code
{post.map(todoList => (
<td><Image src={todoList.image} width={5}
height={50}/> </td>
))}
Open your next.config.js file and put your domain where images are stored like below:
const nextConfig = {
reactStrictMode: true,
presets: ["next/babel"],
images: {
domains: [
"diggdevelopment.com",
]
}
};
module.exports = nextConfig;
You can check if post is empty or not using below codes:
{post.length > 0 ? (
post.map((todoList, index) => (
<td key={index+1}>
<Image src={todoList.image} width={5} height={50} />
</td>
))
) : (
<p>No data</p>
)}
index will give you numeric value from 0 to the length of the array
Need to add the loader function
This will generate the URLs for your image. It appends a root domain to your provided src
<td><Image loader={() => todoList.image} src={todoList.image} width={5}

Angular - Use a default image if image does not exist on server

I have a component that will display a cover image. The user can upload a cover image and the component will display the user uploaded image. If the user doesn't upload an image, then I want to display a default image.
If there is no user uploaded image I want to return an error and call the changeSource(event), which should in theory bind a new image url to the img src. However I'm getting undefined for the event.target.src and I'm seeing a blank space where the default image should be. It works fine when displaying the custom image.
component.html
<div *ngFor="let coverPhoto of coverPhotos">
<img src="{{coverPhoto}}"
(error) ="changeSource($event)" />
</div>
component.ts
this.myService.getPhotos(ImageType.Cover, this.id).subscribe(result => {
this.coverPhotos = result;
}, error => {
this.errors = error;
this.changeSource(event);
}, () => {
}
);
changeSource(event) {
event.target.src = "https://imageurl";
}
directly use (where defaultImage is a variable in ts file which holds the default image path) -
(error)="$event.target.src = defaultImage"
your HTML -
<div *ngFor="let coverPhoto of coverPhotos">
<img src="{{ coverPhoto }}" (error)="$event.target.src = defaultImage" />
</div>
Working example here.
You are passing event from this code in ts, which is obviously undefined, and you don't need to call this function from here -
this.myService.getPhotos(ImageType.Cover, this.id).subscribe(result => {
this.coverPhotos = result;
}, error => {
this.errors = error;
this.changeSource(event);
}, () => {
}
);
The *ngFor was throwing it off. Removing this seemed to solve the problem. Not quite sure why so will post an edit when I discover why.
<div>
<img src="{{coverPhotos}}"
(error)="$event.target.src = defaultImage" />
</div>

why image doesn't show up

I'm trying to feed image path through property path and render it. I have many images and I want to set the image in runtime so I cannot use pre import the image prior to rendering. But the image does not show.
Error: cannot find module (but path is correct)
but when I replace the varible path to actual path as var imageName = require('./Assets/profpicjpg.jpg').default; then image shows up, but I wanna use the variable path to feed the variable path data
Rendering this
import Profpic1 from './Components/Public-page/Profile-card';
function App() {
return (
<div className="App">
<Profpic1
path = './Assets/profpicjpg.jpg'
/>
</div>
)
}
export default App;
Function (this is in a different page)
export default function Profpic1 ({path})
{
var imageName = require(path).default;
return (
<div>
<img src={imageName} />
</div>
)}

retrieving images from data return in vuejs

im trying to display som images in my code , already stored in my data in this way:
<div >
<tr v-for='(ships,index) in destroyedShipBox' :key='index'>
<td>{{ships}}</td>
<div v-for='(links,index1) in destroyedShipBoximages' :key='index1'>
{{links.type==ships?links.src:''}}
</div>
</tr>
</div>
where my data stores this arrays of objects:
data() {
return {
destroyedShipBox:['PatrolBoat','Destroyer'],
destroyedShipBoximages:[
{type:'PatrolBoat',src:require('../assets/patrolBoatHorizontalView.png')},
{type:'Submarine',src:require('../assets/submarineHorizontalView.png')},
{type:'BattleShip',src:require('../assets/battleshipHorizontalView.png')},
{type:'Carrier',src:require('../assets/carrierHorizontalView.png')},
{type:'Destroyer',src:require('../assets/destroyerHorizontalView.png')},
],
}
the destroyedShipBox gets fill automatically with some JSON already fetched then destroyedShipBoximages is just a collection of all type of ships in game as well as a image of its according to its type.
Thus my logic in the html template wants to set an image attuning with the kind of ships i already got in the destroyedShipBox array , but the the final result is this
PatrolBoat /img/patrolBoatHorizontalView.63b25d8d.png----->should be an image instead of this
Destroyer /img/destroyerHorizontalView.396ed25f.png ----->should be an image instead of this
simply the image don't appear...
Any advice about how to solve this problem...
thanks in advance!!!!
you can also ease up your template logic and have only one if condition if there is a 1:1 relation between ships and their images with the following computed property:
computed: {
shipsWithImages() {
return this.destroyedShipBoximages.filter((value) => {
if(this.destroyedShipBox.includes(value.type)) {
return value;
}
})
},
}
Cheers,
ewatch
You should assign links.src to src attribute of img tag like this:
<div>
<tr v-for='(ships,index) in destroyedShipBox' :key='index'>
<td>{{ships}}</td>
<td>
<div v-for='(links,index1) in destroyedShipBoximages' :key='index1'>
<img :src="links.src" v-if="links.type==ships"/>
</div>
</td>
</tr>
</div>

Modify Image Url Value with Vue Js in a Loop

I have a simple Loop with conditionals. I want to modify the full url to a version of the image with 60x60 pixels.
Full image url : www.example.com/img/full-image-001.jpg .
Modified image url that I need : www.example.com/img/full-image-001-60x60.jpg .
<template v-else-if="column === 'product_img'">
<img :src="replaceLink.columnValue" alt="" height="60" width="60">
</template>
Method function:
methods : {
replaceLink (record) { //logic
}
}
EDIT :
Is this the proper way ?
methods: {
replaceLink (record) {
let res = record.replace(".jpg", "-60x60.jpg");
console.log(res);
}
},
Better solution is to create filter and use it on your images.
Instead fo methods object create filters object with replace function:
filters: {
replaceLink: function(value) {
if (!value) return '';
return value.replace('.jpg', '-60x60.jpg');
}
}
And now in your HTML you can use it like this:
<img :src="source | replaceLink" />
You should have source in your component data or you will get an error. This source should be image url

Categories