Is there a way to set the image result retrieved from the API call as the background image for my app?

In my current project, the user is able to input a city and the background of the page changes to display an image of that specific city. This image is obtained through an API call to Pixabay API, with the result stored in a variable named "background". However, I'm facing an issue in appending this background image to the entire page. When I console.log(background), I get the URL of the desired background image that I want to apply to the page.

import React, { Component } from "react";
import Title from "./Title.js";
import Form from "./Form.js";
import Weather from "./Weather.js";
import axios from "axios";

// import logo from "./logo.svg";
import "./App.css";

const API_KEY = "b6907d289e10d714a6e88b30761fae22";
// const API_ID = "12653279-f2ae53f8bfb342d39b6cbf92b";

class App extends Component {
  state = {
    temperature: undefined,
    city: undefined,
    description: undefined,
    error: undefined,
    searchText: "",
    apiUrl: "https://pixabay.com/api",
    apiKey: "12653279-f2ae53f8bfb342d39b6cbf92b",
    images: []
  };
  
  // Code for fetching weather data
  
  render() {
    return (
      <div className="container">
        <Title />
        <Form getweatherData={this.getweatherData} />
        <Weather
          temperature={this.state.temperature}
          city={this.state.city}
          country={this.state.country}
          description={this.state.description}
          error={this.state.error}
        />
      </div>
    );
  }
}

export default App;

Form.js

import React, { Component } from "react";

class Form extends Component {
  render() {
    return (
      <form onSubmit={this.props.getweatherData}>
        <input type="text" name="city" placeholder="City..." />
        <button>Get Weather</button>
      </form>
    );
  }
}

export default Form;

Answer №1

First, store the background image in a state variable and then apply it as an inline style to the desired element. Here is an example:

...
const backgroundImage = response.data.images[0];
this.setState({ backgroundImage });
...
return (
    <div className="container" style={{ this.state.backgroundImage ? { backgroundImage: `url(${this.state.backgroundImage})` } : {} }}>
...

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

Issue with Bootstrap.js causing mobile menu to not expand when toggled in Rails app

Despite adding the .toggled class, my hamburger menu is not expanding when I click on the mobile menu. I've tried adjusting the order of the required javascript commands, but it doesn't seem to be working as expected. Here are the steps I'v ...

JavaScript code for initiating the npm start command

Is it possible to include the npm-start command in a JavaScript script? Requirement: Develop a JS script capable of triggering the npm-start command. Operating System: Microsoft Windows I need to turn it into a Windows service. However, in the code snip ...

Vuejs: Users can still access routes even after the token has been deleted

Upon logging out of my application, I have encountered a peculiar issue. Certain inner links, such as those within a user's panel, remain accessible even after I have logged out and deleted a token. However, other links are not. Any suggestions on how ...

Scroll Magic not cooperating with Simple Tween local copy

Greetings! I am attempting to replicate this simple tween example using scrollmagic.js. It functions properly on jsfiddle. To confirm, I added scene.addIndicators() to observe the start, end, and trigger hook. It functions flawlessly. As displayed in the ...

Combining SlateJS with Redux

I need to store the value of a SlateJS editor in redux instead of state, but when I modify the hasLinks method, I encounter an immediate crash with the error message: TypeError: Cannot read property 'inlines' of undefined Modified Editor&apos ...

What is the best way to retrieve the value of a specific textfield using the map function with a collection of

These posts have identical text fields for comments, using the same useState hook. I am trying to extract the value of a specific text field without affecting others. It's similar to Facebook posts, but I'm unsure how to achieve this. const PostT ...

Looking for a way to interact with the React Query `queryClient` without being inside the provider? For instance, you may want to invalidate queries during

Is it feasible to interact with my application's React Query queryClient outside of React? During some of my Cypress tests, I perform data fetching or manipulation and then wish to clear all or part of the queryClient cache. Is this achievable? I ha ...

Merging Technology: Integrating Maps into Hybrid Applications

Currently, I am developing a mobile application using React-Native with a main focus on: Map Integration: Partial Success - I have successfully implemented all features mentioned in this link. The remaining task is to display live routing based on curren ...

implementing asynchronous function inside useEffect to fetch previous property

Here's some code snippet that I'm working with: let props.n default = 1 function consoleLog() { dispatch({n: 2}); useEffect(()=> { async function c() { ...

Creating dynamic forms using AngularJSIn this tutorial, we will explore how to generate

I need help creating an HTML form. I have an object that stores an array of form elements like { "formFields": [ { "type": "select", "label": "Fabric", "name": "fabric", "options": [ ...

Enhancing Efficiency and Optimization with jQuery

Recently delving into the world of jQuery, I have been on the lookout for ways to enhance the speed and performance of my code. If anyone has any tips or valuable resources that could aid me in this endeavor, I would greatly appreciate it. Thank you, Bev ...

What is the best way to combine this PHP, Javascript, and HTML document together?

My goal is to upload a CSV file exclusively using an HTML form and then save it in an array using PHP and Javascript. I have individual codes that work perfectly when used as separate files. However, when I attempt to combine them into one file, the Javas ...

issue encountered when trying to include a new task to a React application's task management feature

I am currently working on a React code to update my to-do list with new items, but for some reason, the output is an empty array. I'm unsure of what's causing this issue. Can someone please provide insight into why my code is not functioning as e ...

The upcoming development does not involve creating an entire HTML webpage using on-demand static site generation (SS

I’m encountering a problem when utilizing getStaticPaths and getStaticProps to create an on-demand SSG for a sharing page. My setup involves Next v12.1.0 and React 17.0.2. After building a specific /[id] page, I can retrieve the data but the HTML output ...

Issue with ToggleButtonGroup causing React MUI Collapse to malfunction

I'm having trouble implementing a MUI ToggleButtonGroup with Collapse in React. Initially, it displays correctly, but when I try to hide it by selecting the hide option, nothing happens. Does anyone have any suggestions on what might be causing this ...

Oops! Looks like there was an error with React: You can't use objects as a

I encountered an issue while attempting to create a login page. Every time I try to log in, I receive this error message. I have attempted to troubleshoot the problem but have yet to find a solution. Error: Objects are not valid as a React child (found: ob ...

Javascript is handling the JSON Request flawlessly, however, when using Nodejs, an error is encountered with a status

I'm trying to fetch a simple JSON File in NodeJS. Using Javascript and jQuery, it functions perfectly: $(document).ready(function() { $.getJSON('https://www.younow.com/php/api/broadcast/info/curId=0/user=Peter', function(json) { if ...

React: Trying to use the map function on an empty array will result in an error

I am currently facing an issue while trying to populate a shopping cart with items. Even though I have initialized the cart as an empty array, I keep encountering the following error: TypeError: cart.map is not a function ProductContext.js:34 addItemToCar ...

When toggling between different themes, the colors in Material-UI remain consistent and unchanged

Currently, I am adjusting the theme within my application by utilizing a state variable with the MuiThemeProvider. When I change to a new theme, all component colors update correctly. However, I have noticed that if I switch back to a previously used theme ...

What is the method for extracting individual elements from an object returned by a React hook in Typescript?

I am currently working on a component that needs access to the query parameters from React Router. To achieve this, I have been using the use-react-router hook package in my project. This is what I am trying to accomplish: import React from "react; impor ...