react js rendering images using props in url - javascript

I want to render images from my server ftp using props in React JS.
I have like:
render(){
console.log(this.props.product.image) //Which gives me the product image name properly
return(
<div className={this.props.openModal ? "modal-wrapper active" : "modal-wrapper"}>
<div className="modal" ref="modal">
<button type="button" className="close" onClick={this.handleClose.bind(this)}>×</button>
<div className="quick-view">
<div className="quick-view-image"><img src={`${this.props.product.image}`} alt={this.props.product.name +' image'}/></div>
<div className="quick-view-details">
<span className="product-name">{this.props.product.name}</span>
<span className="product-price">{this.props.product.price}</span>
</div>
</div>
</div>
</div>
)
}
In the log i am getting the image name, but why not the same in the img src attribute.
I tried to give the same line in src like i have given in console.
But just gave a try like:
Log data:

Ok i updated the full path, now image is rendering.
<img src={'http://localhost:5000/images/products/'+this.props.image}

Related

How to use iterativa data path in v-for loop (Vue)

I am a beginner of Vue
I would like to use my iterative image file name as "room1.jpg", "room2.jpg", "room3.jpg" ...
This is my code, the second line is the problem
<div v-for="(p,i) in products" :key="i">
<img src= "./assets/room"+str(i)+".jpg" class = "room-img">
<h4 #click="modelFlag = true">{{products[i]}}</h4>
<p>{{prices[i]}}</p>
<button #click="increase(i)">sign</button>
</div>
In Pyhton, I usually use for this
for i in range(number):
"./assets/room"+str(i)+".jpg"
Is there any similar way to this?
You've to bind variable data into your src as follow
<div v-for="(p,i) in products" :key="i">
<img :src="`./assets/room${str(i)}.jpg`" class = "room-img">
<h4 #click="modelFlag = true">{{products[i]}}</h4>
<p>{{prices[i]}}</p>
<button #click="increase(i)">sign</button>
You can perform/do above as follow too:
:src="'./assets/room'+str(i)+'.jpg'"
And it will works.
:src and v-bind:src work in same way
Reference
https://vuejs.org/api/built-in-directives.html#v-bind

Giving random background images to each div in the for loop in Vue Js

I have a v-for loop that runs on a div and gives out a bunch of tags. I need each of those tags to have a different src. Everything that I have tried so far results in all the tags getting the same source. Is there any way I can do this?
<div class="wrapper" v-for="result in results" :key="result.index">
<div class='small-card'>
<img class="thumbnail" :src="backgroundImage">
<div class="text-elements">
<span class="md-display-2 minicard-title">{{result.name}}</span>
<br class="break">
<span class="md-display-1 minicard-subtitle">{{result.state}}</span>
</div>
</div>
<br class="br3">
</div>
I recently did this in a project.
What I ended up doing was setting the style tag for background-image using the :style attribute.
Depending on how you are acquiring the image source, you will need to either create a method to return a random image URL, or access the image URL provided in the object. As you said "random" I assume the first approach would be the best fit.
Here's a very rough and untested example:
<template>
<div>
<div
v-for="index in 10"
:key="index"
:style="{'background-image': randomImage()}"
/>
</div>
</template>
<script>
export default {
name: 'Example',
data() {
return {
images: ['1.jpg', '2.jpg', '3.jpg', '4.jpg'],
};
},
methods: {
randomImage() {
return `url("${
this.images[Math.floor(Math.random() * this.images.length)]
}")`;
},
},
};
</script>
Make sure that the :style="{'background-image': randomImage()}" contains a () to ensure the method is called vs being referenced.

How to dynamically add a component on link click in my Angular application

I have three components: (1) a navigation bar, (2) home page with a left and right div, and (3)view-associates. On link from the navbar, I want to dynamically add the view-associates component into the home's right div. I have already implemented the following code (in the traditional JavaScript fashion) into the navbar-component.ts file:
addTemplateTag(){
const link = document.querySelector('.nav-link');
const showArea = document.getElementById('showArea');
console.log(link);
console.log(showArea);
// check for specific class name to get appropriate template tag
if (link.classList.contains('view-associates')){
console.log('Found view-associates class in link. Getting tag...');
// NOTE: the below two lines did work BUT still did not show component
const templateTag = document.createElement('app-view-associates');
showArea.appendChild(templateTag);
}
}
Here is the HTML code with the navbar and home components, respectively:
navbar.component.html
<nav class="nav flex-column">
<a class="nav-link view-associates" (click)="addTemplateTag()">View My Associates</a>
</nav>
home.component.html (Before link click)
<div class="container-fluid">
<div class="float-left left">
<h1 class="title">Welcome</h1>
<app-nav-bar></app-nav-bar>
<button class="btn btn-primary logout-btn" (click)="logOut()">Log Out</button>
</div>
<div id="showArea" class="float-left right">
</div>
</div>
home.component.html (After link click)
<div class="container-fluid">
<div class="float-left left">
<h1 class="title">Welcome</h1>
<app-nav-bar></app-nav-bar>
<button class="btn btn-primary logout-btn" (click)="logOut()">Log Out</button>
</div>
<div id="showArea" class="float-left right">
<app-view-associates></app-view-associates>
<-- ^^^ appended but component not showing -->
</div>
</div>
Here's the images of the home page before and after the link click:
Before (with browser console)
After (with browser console)
This above code did work but still did not show the view-associates component at all. How do I resolve this issue? Any advice is appreciated.
Use ngIf and ngSwitch to show/ hide components dynamically. For example : -
in .html
<app-form></app-form>
<some-component *ngIf="isLoggedIn"></some-component>
<some-component *ngIf="!isWorking"></some-component>
<another-cool-component *ngIf="!isLoggedIn"></another-cool-component>
in .ts
export class MyFunnyComponent implements OnInit {
isLoggedIn = false;
cartValue: number;
constructor() {
}
ngOnInit(): void {
}
}
Obviously there are some other ways to handle these scenarios but, for the start it might be enough. We might also have to pass data from child to parent and vise versa.

Using generic array name in template

I am really new to vue.js and HTML. I have two components that are working together. A photo-gallery and a tag-component. The tag-component uses the tags array to get the tags for a image. What i would like is to have a tag array for each image. I figured i could use the imageIndex and append that to the array name so I was string something like :tags=tags+imageIndex.
But if I do that, it does not work (i think it is not recognized as an array any more...) . My question is, is there a way to enter that in to the template, so that i have for each image an array with the name tags{index}?
Many thanks for the help!
Robin
<div id="SingleFile">
<button
id="refreshbtn"
class="btn btn-primary btn-margin"
#click="updateFileList">
refresh
</button>
<gallery :images="images" :index="index" #close="index = null"></gallery>
<div
:key="imageIndex"
:style="{ backgroundImage: 'url(' + image + ')', width: '300px', height: '200px' }"
#click="index = imageIndex"
class="image"
v-for="(image, imageIndex) in images"
>
<div>
<vue-tags-input
v-model="tag"
:tags="tags"
#tags-changed="newTags => tags = newTags"
/>
</div>
</div>
<div class="upload">
<upload-image url="http://localhost:8080/user" name="files" max_files="100"></upload-image>
</div>
</div>
You could use a method to achieve that:
<vue-tags-input
v-model="tag"
:tags="getTags(imageIndex)" ... >
and define it like :
methods:{
getTags(i){
return this['tags'+i];
}
}
by assuming that you have in your data object something like :
data(){
return{
tags0:[],
tags1:[],
...
}
}
or any property which has that syntax tags+index

change img that in class in class in id

I read about it but still I'm not able to make it work.
I have an image (empty heart) that I would like to change to a different image (full heart) in order to indicate it was added to the wish list.
here is my code:
<tbody class="mainImgs">
<div ng-repeat="party in showtop5" ng-class=party.name>
<img ng-src="{{party.image}}">
<h2 id="title">{{party.title}}</h2>
<h3 id="description">{{party.description}}</h2>
<button href="#" class="imageClick" ng-click="click(party.title, party.description, party.image)">
<img ng-src="../images/emptyHeart.png" id="heart" click="myFunction(party.name, imageClick)">
</button>
<img ng-src="{{party.img}}" id="pace">
</div>
</tbody>
and my script:
function myFunction(myclass1, myclass2){
document.getElementByClass(myclass1).getElementByClass(myclass2).getElementById("heart").src = "../images/fullHeart.png";
}
what did I do wrong?
without sending the class - and trying to find image only by id - t works only for the first object heart that is printed
I think if its just about changing image then it can be handled pretty straight forward:
In html
<button href="#" class="imageClick" ng-click="click(party.title, party.description, party.image)">
<img ng-src="{{imgPath}}" id="heart" ng-click="myFunction(party.name, imageClick)">
</button>
In Controller:
$scope.imgPath = "../images/emptyHeart.png";
$scope.myFunction= function (name,imageClick){
// use promise to monitor the server response of adding product to Wishlist
("YOUR_PROMISE_CALL").then(
function(success){
$scope.imgPath = "../images/fullHeart.png"; // Bingo !!
},
function(error){
// take appropriate action
},
)
}

Categories

Resources