React - dynamically set backgroundImage from JSON response - javascript

I am getting data from my Wordpress API to display in my react app. I am trying to display the post featured image as a background-image on an element and can't seem to get it to work.
Here's an example of the JSON response:
{
"id": 1,
"title": {
"rendered": "My First Post"
},
"featured_image": "http://example.com/wp-content/uploads/2019/08/featured.jpg"
}
And here's what I have tried based on this question to set the background image:
<div className="featured-image" style={{backgroundImage: 'url(${this.props.post.featured_image})'}}></div>
When I inspect the element, it appears that the JSON isn't being parsed because this is what it looks like:
<div class="featured-image" style="background-image: url("${this.props.post.featured_image}");"></div>

You are using as string, not template string.
Try this:
<div
className="featured-image"
style={{
backgroundImage: `url(${this.props.post.featured_image})`
}}>
</div>

Related

ReactJs not rendering anchor tag as a link when anchor tag comes inside the string response

I am new to react js and shifting our code from Freemarker to react
I am getting a Json string response which contains anchor tags, when I render this string in react js on browser it shows the anchor tag as a plain text not as a link.
Response:
{
"type": "paragraph",
"paragraph": {
"body": " <p> Jaguar Land Rover has officially taken the covers off the fifth generation Range Rover SUV which now comes with a new look, new engine options and loaded with new technology with features galore. </p>"
}
}
ReactJS Code:
<div className="StoryBodyContent" id={`story_$${storyData.id}`}>
{storyData.listElement.map(element =>
(
<p>{element.paragraph.body.replace("<p>","").replace("</p>","")}</p>
))
}
</div>
ReactJS Output:
Expected Output:
A better implementation would be getting the data you pass to your a tag and transfer it to your JSON data as additional properties instead of passing
the whole anchor tag with data inside.
Refactored Code:
JSON DATA:
{
"type": "paragraph",
"paragraph": {
"body": {
"firstLink" : "http://stg-testing.com/new-cars/jaguar",
"secondLink" : "http://stg-testing.com/new-cars/landrover",
"firstLinkText" : "Jaguar",
"secondLinkText" : "Land Rover",
"children" : has officially taken the covers off the fifth generation
Range Rover SUV which now comes with a new look, new engine options
and loaded with new technology with features galore"
}
}
}
REACT.JS
<div className="StoryBodyContent" id={`story_$${storyData.id}`}>
{storyData.listElement.map(element =>
(
<p><a href={element.paragraph.body.firstLink}>
{element.paragraph.body.firstLinkText}
</a>
<a href={element.paragraph.body.secondLink}>
{element.paragraph.body.secondLinkText}
</a>
{children}
</p>
))
}
</div>
Try setting the innerHTML instead of rendering this as a string.
<p dangerouslySetInnerHTML={
element.paragraph.body.replace("<p>","").replace("</p>","")
}></p>
Read the documentation for more details.

how do I set a background image on div in react js?

I'm trying to set a background image that changes per card element. The website is a recipebook, basically I just want each individual card to be the image of the recipe.
import React from "react";
import "./card.css"
const Card = ({recipe}) => {
return (
<div className="card-bg tc dib br3 pa3 ma2 grow bw2 shadow-5" style={{backgroundImage: `url("${recipe.img}")` }}>
<p className="test">{recipe.name}</p>
<p className="desc">
Recipe type: {recipe.type}
</p>
<p className="desc">
Author: {recipe.author}
</p>
<p className="desc">Recipe Link</p>
<hr />
</div>
);
};
export default Card;
I'm not getting any errors from this, but nothing is changing in the background. What am I doing wrong?
fyi, the image path is located in the json file as per below, per recipe:
{
"id": 1,
"name": "Carrot cake",
"type": "sweet",
"author": "Grandma",
"link": "recipes/carrotcake.html",
"img" : "../img/carrot.jpg"
},
Thanks in advance!
EDIT: The background property is showing in chrome devtools on inspection, it just isn't visible.
EDIT:EDIT: I've discovered that I can move the IMG folder anywhere in the project and not change the image path, and despite this, chrome developer tools still shows the background property on the DIV at the original path, yet doesnt throw an error...
Seems like you made mistake in style={{backgroungImage: url("${recipe.img}")
Change g with d. If it does not fix and you are using API to get the image, I would recommend you to check API to see image part.
Try moving the img folder into the public folder of the react app, and change the file path to '/img/carrot.jpg'.
I had this same issue a while back, and I think this is what fixed it.
backgroundImage: `url(${Background})`

Problem loading an image dynamically with Vue & Webpack

I started building an application with the Vue CLI, and I have the following code snippet in a component:
<template>
<div v-loading="loading">
<el-carousel :interval="4000" type="card" height="350px">
<el-carousel-item v-for="element in persons" :key="element.id">
<div class="testimonial-persons">
<el-avatar :size="80">
<img :src="require('#assets/testimonial/'+ element.photo)">
</el-avatar>
<h3>{{element.name}}</h3>
<h4>{{element.occupation}}</h4>
<hr style="width:50%;">
<p>"{{element.comment}}"</p>
</div>
</el-carousel-item>
</el-carousel>
</div>
</template>
When the page is loaded I make a request for an API that returns an array of objects that I store in persons to iterate over the template.
Persons
[
{
"testimonial_id": "2",
"persons_id": "1",
"id": "1",
"name": "Tom lima",
"occupation": "CEO / Pugmania",
"comment": "Simply the best customer service and attention to detail.",
"photo": "20200320193143R7pChVea3IkmujRRmS.png"
},
]
Everything works normally, the problem is with the image loading.
When I enter the image name manually it works.
<img src="#assets/testimonial/20200320193143R7pChVea3IkmujRRmS.png">
Does anyone have any idea how to solve?
Your template is correct except that you're missing a / following the #. It should be:
<img :src="require('#/assets/testimonial/' + element.photo)">
This would be needed for the manual usage too, so maybe you left it out when you converted it to a dynamic path.

How do you populate a hidden div using handlebars data?

The handlebars data shows up fine on the static page, but the problem is I also have a modal, and the data is not being populated correctly on the modal.
I am using the avgrund modal (you can view the Codepen here)
main.js - handlebars code
var projectData = [
{
id: "0",
name: "Jack",
},
{
id: "1",
name: "Sally",
},
];
var theTemplateScript = $("#project-template").html();
var theTemplate = Handlebars.compile(theTemplateScript);
$("#content").append(theTemplate(projectData));
index.html
<div id="content">
<script id="project-template" type="x-handlebars-template">
<div class="pile">
{{#each this}}
<a onclick="avgrund.activate( 'stack' );">
<div class="box box{{id}}">
<span class="project_name project_name{{id}}">{{name}}</span>
</div>
</a>
<aside class="avgrund-popup">
<h2>{{name}}</h2>
<p>
You can hit ESC or click outside to close the modal. Give it a go to see the reverse transition.
</p>
</aside>
{{/each}}
</div>
</script>
</div>
Problem
The div boxes will show up fine, but whenever I click the boxes so that the modal appears, the modal only displays the last element in projectData.
I've been able to have the data appear fine when I use bootstrap modals, but for some reason not the avgrund modal.
Hint at a possible solution?
I think the answer to this StackOverflow q: how to populate hidden form field hints as something that might work, e.g. pulling out the data and re-inserting it in the avgrund modal code, as such
var data = {
"Value": [
{"Id": "6b7", "Notes": "testing", "CreatedBy": "User1"},
{"Id": "6b7", "Notes": "Testing 1", "CreatedBy": "User2"}
]};
data.Id = data.Value[0].Id;
var tmpl = Handlebars.compile($('#template').html());
var html = tmpl(data);
But I don't fully understand the answer and wasn't able to get it to work. Could someone point to some approaches or guiding principles that might be helpful?
Here's a fiddle that shows a working example: http://jsfiddle.net/9f9w1trs/
As pointed out by Roamer-1888 you had an extra closing </div> in there. You didn't include the code that actually compiles the template and populates it.
The basic idea is that you define a template - like you did
<script id="project-template" type="x-handlebars-template"> ....</script>
Then you "compile" the template (you can pre-compile them for performance reasons or if you'd like to only use the lightweight run-time library opposed to the full library).
var source = $("#project-template").html();
var template = Handlebars.compile(source);
and then you can populate your template with data ...
var populatedHtml = template(projectData);
and finally you add your populated HTML to the DOM
$('#myContent').append(populatedHtml);
Handlebars doesn't really care if you add it to a hidden div or not - it just replaces contents between {{}} ;)

angular Failed to load resource error in inspector

I am uploading dummy content using angular's ng-repeat.
var app = angular.module("homeApp", []);
app.controller("entriesView", function ($scope){
$scope.itemEntry = [
{
image: "img/112013-priscilla-600.jpg",
title: "ymc",
logo: "http://www.youmustcreate.com/site/wp-content/themes/youmustcreate/images/core/header-logo.jpg"
},
{
image: "https://cms.myspacecdn.com/cms/x/13/47/112013-priscilla-600.jpg"
}
];
});
HTML
<section class="miniframe-wrapper" ng-controller="entriesView">
<section ng-repeat="itemEntry in itemEntry" class="miniframe">
<img src="{{itemEntry.image}}" alt="img"/>
I noticed in inspector i am getting the Failed to load resource error however the images are appearing on my browser. Does anyone know what exactly is causing this issue. am i referencing my images correctly?
Use ng-src instead of src in your image tags when using string interpolation. ng-src parses the string then assigns the src to the tag while vanilla html is looking for an image called "{{dataEntry.image}}"

Categories

Resources