Looking to dynamically set a background image using data fetched from an API in a ReactJS project

Looking to incorporate a background image from an API response in ReactJS

Here is some sample code:

useEffect(() => {
axios.get(`https://apiaddress=${API_KEY}`)
.then(res=>{
    console.log(res);
    setRetrieved(res.data);
    console.log(retrieved);
  
})
.catch(err=>{
    console.log(err)
})
     return(
    <div ClassName="home" style={{backgroundImage:`url({retrieved.imageurl}{/*or 
    any other var of type string*/}), width: 1920, height: 1080 } </div>

Attempting to store the retrieved image in a variable, everything seems to be functioning properly but the image (received in the response) is not displaying as a background.

Answer №1

Revamp your styling attribute

style={{backgroundImage: `url('${retrieved.imageurl}')`}}

Answer №2

If you're dealing with an image retrieved from an API, consider using this method:

return(
<div ClassName="home" style={{backgroundImage:"url(" + retrieved.imageurl + ")", width: 1920, height: 1080 } </div>

I found inspiration for my solution from this code snippet: Setting a backgroundImage With React Inline Styles

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating an indentation on one side of a div using CSS for a visually appealing effect

https://i.stack.imgur.com/io6m0.jpg I'm in the process of trying to create two shapes using CSS. I've been able to almost achieve the first shape on the left, but it extends out too far. As for the second shape, I'm having difficulties cre ...

How can I place text on top of an image with a filter using Bootstrap?

I am facing a challenge of overlaying text on an image with a tinted background color and opacity. While working with Bootstrap 4, I suspect that some classes might be conflicting with each other. This is my current setup: Index.cshtml: <div class=" ...

Preserving data in input fields even after a page is refreshed

I've been struggling to keep the user-entered values in the additional input fields intact even after the web page is refreshed. If anyone has any suggestions or solutions, I would greatly appreciate your assistance. Currently, I have managed to retai ...

Using Props with jQuery in React Components: A Comprehensive Guide

I trust you comprehend this straightforward example. I attempted to modify the background color of my HTML element during initial rendering by managing it in a React Component with a touch of jQuery assistance. Here is the code within my React Component ...

Having trouble receiving a complete response when making an ajax request to fetch an entire webpage

Currently, I am experimenting with J-Query Ajax functionality. My goal is to send a request in order to retrieve the entire HTML data of a page that I have hosted on bitbaysolutions.com. The issue arises when I load this URL and execute document.getElement ...

Error encountered during GitHub action for building and deploying to Firebase

Every time I push to my GitHub repo, I encounter this error. The build works fine on my machine, but when using actions, I keep running into a memory issue. I've successfully used this on other repos before and it worked perfectly, so I'm stumpe ...

To determine the class of an element and reveal its parent if the class is present

Typically, the parent element remains hidden by default. However, upon clicking a specific element, its child might gain a class called "selected". How can I check for this class and then display the entire list if it is present? <ul style="display: ...

Angular2 - HTML not displaying the response

I am currently mastering angularjs2. In my latest project, I attempted to fetch data from an API and received a response successfully. However, I encountered an issue where the response is not rendering in homepage.component.html as expected. I am unsure o ...

The trio of Javascript, Ajax, and FormData are

I'm struggling with sending form values to a PHP file. Here's the code I have: <form role="form" id="upload_form" method="post" enctype="multipart/form-data"> <div class="form-group"> <label for="formlabel">Title< ...

Lazy Load immediately loads images that are visible on the screen without needing a click

I am facing an issue with Lazy Load on my image-heavy website. I want the images to load only when a button is clicked, but currently, it only partially works. Images below the fold follow the desired behavior of loading on click, but those above the fold ...

Conditionally Add Columns to jQuery Datatables

I am working with a jQuery datatable to showcase data retrieved through an AJAX request. However, I am interested in adding a third column to the table specifically for administrators, allowing them to delete entries. Can someone guide me on how to incorpo ...

Stopping the parent onclick event from propagating to a child element within a bootstrap modal

I am currently working with angularjs and bootstrap, incorporating nested onclick events using Angular's ng-click in various HTML elements. One is located in a table header to display different sort icons and execute the sorting logic when the header ...

The function res.headers is not available for use, therefore jwt.sign cannot be utilized in this

I am encountering an error (res.headers is not a function) with the following code when using jwt.sign. Any ideas on how to resolve this issue? Could it be related to syntax? app.post('/logIn', async (req, res) => { //Checking if email exist ...

Create a PDF document using HTML code stored on a separate component within an Angular 2 application

I am facing an issue with my parentComponent and childComponent setup. Specifically, I have a button called downloadPDF in the parentComponent that is supposed to trigger a PDF download from the HTML code of the childComponent without displaying the childC ...

Accessing a Kendo Grid instance within an Angular directive

Continuing from the previous question, which can be found here, I have an additional query that I felt warranted a separate post. The link provided above demonstrates how to obtain a grid instance in Angular, credit to Lars for that. Building upon the ex ...

Generating a new root in React 18 results in numerous rounds of rendering and execution

Every time I attempt to run this code in React 18, it seems to render multiple times unlike React 17 where it only executes once and functions properly. How can I modify the code so that it only runs once? Is there a specific reason for the multiple execu ...

What could be causing a blank page to appear after being redirected? (Using NextJS 13 API Route)

After struggling with this issue for 2 days, I'm throwing in the towel and reaching out to the community for assistance. I've been tasked with setting up a basic login system for a new project using NextJS v13. However, it seems like a lot has c ...

Parse a string and generate an array using regular expressions in JavaScript/Node.js

I'm currently working on coding in JavaScript to extract an array of elements after splitting using a regular expression. var data = "ABCXYZ88"; var regexp = "([A-Z]{3})([A-Z]{3}d{2})"; console.log(data.split(regexp)); The current output is [ &a ...

The Jquery script is ineffective for newly added elements

After creating an Ajax Form that functions well, I noticed that when the result of the form is another form, my script does not work for the new form generated. Is there a way to make the new form function like the old one? $(document).ready(function() ...

The onchange event does not seem to be functioning as expected in a dropdown menu that was dynamically added from a separate

Is there a way to display a list of tables from a database in a dropdown menu and allow users to select a table name? When a user selects a table name, I would like to show all the data associated with that table. The HTML file structure is as follows: & ...