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

The Forward and Back Buttons respond based on the current position of the caret

Exploring the concept of a Keypad-Login. I am trying to create Back and Forward buttons. However, the back and forward buttons are currently inserting the letters at the end of the input value instead of at the caret position. The input field is disabled, ...

The issue of page content failing to refresh when loaded using AJAX technology

My script utilizes AJAX to dynamically load specific pages on a website. These pages display information that updates based on the current time. However, I have encountered an issue where the page content remains static when loaded through AJAX, almost as ...

AngularJS ng-click incompatibility causing non-functioning popover content

I've gone through all the posts regarding this issue, but unfortunately, none of them proved to be helpful. It seems that the jsfiddle and plunker links provided are no longer functioning as expected. My objective is quite simple - I want to place a ...

Looping through elements using JQuery in groups of 2

Let's say I have the following array: Mike Blue Jakob Red Luis Orange and I'm using this JQuery code to loop through it: $.each( arr, function( index, value ){ $( ".div" ).append( "" + value + "" ); } }); Now, I want to modify the ...

"Run npm install to add fsevents to your project dependencies

Hey there, I'm currently in the process of setting up fsevents using npm. Here are the versions I'm working with: Node : 4.2.6 NPM : 3.5.2 OS : Ubuntu 16.04 LTS I'm running the following command: Edited npm install fsevents --no- ...

Implementing JQuery to Traverse Through JSON Data in AJAX Response

I am currently working on an AJAX call that retrieves JSON data from a query: <script> function retrieveTrips(){ // Fetching the history of trips $.ajax({ url:'cfcs/mileagedata.cfc?method=getTrips&returnform ...

When querying the model, the result may be undefined

I'm encountering an issue where I can't access the content of an array of documents in my model and it's returning undefined. Here is the model structure (Project.js): var mongoose = require('moongoose'); var Schema = mongo ...

Enhancing text visibility in dompdf by making it bold or increasing its size

Recently, I began using dompdf v0.6.0beta3 along with the dompdf Codeigniter helper in Codeigniter. To address the issue of missing fonts, I manually moved the Arial font family tff files from the Windows 7 font folder to the /lib/fonts directory within do ...

What are some ways to prevent manual page reloading in Node.js when using EJS?

Currently, I am utilizing Node as a server and frontend in EJS. My project involves working with socket.io, which is why it is essential that the page does not refresh manually. If a user attempts to reload the current page, the socket connection will be d ...

Creating Varied Results Depending on State Values

I'm in the process of developing a quiz system where different selections lead to distinct outcomes, but I'm facing an issue where the output remains the same. What might be causing this problem? As an example, a user chooses between button 1 an ...

Spacing the keyboard and input field in React Native

Is there a way to add margin between the input and keyboard so that the bottom border is visible? Also, how can I change the color of the blinking cursor in the input field? This is incorrect The keyboard is hidden ...

Styling Rules for WebKit Browsers

Is there a method to apply a particular CSS style for a div based on whether the user is accessing the page from a Chrome browser on a Desktop or an Android device? .myDIV{ [if CHROME???] width: 280px; [if ANDROID???] width: 100%; } Seeking guidance on ...

The outcome of the JQuery function did not meet the anticipated result

Here is the code I am using: $("p").css("background-color", "yellow"); alert( $("p").css("background-color")); The alert is showing undefined instead of the expected color value. I have tested this code on both Google Chrome and Firefox. Strangely, it w ...

Error in Laravel npm package

Working on my Laravel project, I encountered an issue while trying to implement a video chat feature using https://github.com/PHPJunior/laravel-video-chat?ref=madewithlaravel.com with laravel-echo-server. Despite trying various solutions, none seemed to wo ...

Guide to creating a personalized TinyMCE plugin in a React JS environment

The code snippet above showcases the TinyMCE editor implementation in React JS: import { Editor} from '@tinymce/tinymce-react'; <Editor className="editor" onKeyUp={onclick} api ...

Guide on Executing a Callback Function Once an Asynchronous For Loop Completes

Is there a way to trigger a callback function in the scan function after the for await loop completes? let personObj = {}; let personArray = []; async function scan() { for await (const person of mapper.scan({valueConstructor: Person})) { ...

Express Node.js application - HTTP request object

Why is the request object typically referred to as "req" and remain consistent throughout the application's lifespan? This variable can often be seen in callbacks with syntax such as function(req, res, next). If I assign a value to this req object, li ...

"Exploring the world of JavaScript through the lens of time

This summer, I have the opportunity to assist a friend with some JavaScript challenges on his website. The main issue seems to revolve around technical difficulties with online form submissions. Unfortunately, there are instances where we struggle to verif ...

Promise resolves prematurely before the completion of the process

Hey everyone, I'm working on a project that requires users to input their target URL for downloading and compressing images. Once the user provides the URL, the process begins downloading images asynchronously one by one into a directory. However, the ...

What is the most effective way to eliminate just the last underscore in a string by employing the

I am currently facing an issue with table cell editing. I have the following code that removes all underscores (_) from a string if it contains "test_1_". However, my requirement is to only remove the last underscore and have the string appear as "test_1". ...