What is the process for setting a background image in a React application?

I need help figuring out how to add a background image to my React app. I've searched for solutions on StackOverflow, but I'm still unsure. The image I want to use is named background.jpeg and it's located in the same folder as my App.js file. Below is the code snippet where I'd like to set the background. Thank you!

return (
    <div>
      <div className = "top">
      <h1>Hit the button to generate a random top 25 all-time cd according to the Rolling  Stone</h1>
      </div>
    <div className =  "Outer">
    <div>
      <img src = {ImageArray[this.state.WhichRecord][0]} width = "400px" height = "400px"/>
      <p></p>
      <button onClick={this.RandomNumber}>Press me for a new album!</button>
      <p>Artist: {ImageArray[this.state.WhichRecord][1]} </p>
      <p>Album: {ImageArray[this.state.WhichRecord][2]} </p>
    </div>
    </div>
    </div>
  );
}
}
export default App;

Additionally, here is the progress I've made with the CSS styling:

.Outer {
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
  top: 50px;
}

.top {
  display: flex;
  justify-content: center;
}

Answer №1

Make sure to encompass your content with a div element and then utilize the backgroundImage property within your render method. The remaining pertinent properties can be specified within your css class.

Tip:

<div style={{backgroundImage: `url(${ImageArray[this.state.WhichRecord][0]}`}} className="bg">
   <p></p>
   <button onClick={this.RandomNumber}>Click for a new album!</button>
   <p>Artist: {ImageArray[this.state.WhichRecord][1]} </p>
   <p>Album: {ImageArray[this.state.WhichRecord][2]} </p>
</div>

css:

.Outer {
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
  top: 50px;
}

.top {
  display: flex;
  justify-content: center;
}

.bg {
   width: 400px;
   height: 400px;
   background-position: center;
   background-size: cover;
} 

Answer №2

You may want to consider adding an <img /> tag with a fixed position and setting the background-size to cover

jsx

import BackgroundImage from "./background.jpeg";

...

return (
    <div>
        <img src={BackgroundImage} />
        {/* Continue with the rest of the application */}
    </div>
)

css

    ...
    img {
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background-size: cover;
    }

Provides more flexibility in how the image is handled...

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

PHP warning: Notice: Offset not defined

After creating an API to retrieve data from a database and display it as JSON in HTML, I encountered some PHP errors while trying to echo the data: Notice: Undefined offset: 80 in /opt/lampp/htdocs/ReadExchange/api.php on line 16 Notice: Undefined offse ...

What Happens When You Click on a Link in Google News Using the Mobile Chrome Browser

When using the Chrome Browser on mobile to open a news link from Google News, a new tab is opened. To return to Google News, users can click on the white-highlighted "left arrow" below or find a small header with a "<" symbol above to navigate back. Ho ...

Triggering the retrieval of complete HTML content by clicking a button in order to load extra elements using Selenium

My goal is to scrape a webpage and gather all the links present on it. The page displays 30 entries and to access the complete list, one must click on a "load all" button. Below is the Python code snippet I'm currently using for this task: from sele ...

I prefer to prevent the page from refreshing once the PHP code is executed

<?php $sendTo = "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="45203d242835292005203d24283529206b2b29">[email protected]</a>"; //Receiver mail $name = ""; //Sender's Name $email = ""; //Sender' ...

Mysterious attributes of angular 6's <table mat-table> tag

This particular question regarding the angular material table has not been duplicated in any other discussions. Other similar questions pertain to angular versions 2-5, not version 6 The issue I am encountering is as follows: Can't bind to 'dat ...

Problem with loading images on an HTML webpage

https://i.sstatic.net/aQ0oD.png After refreshing the page, I'm encountering an issue where the image is not loading. However, if I switch tabs from MEN to WOMEN and back again, the image will display without any problem. Even making changes in the CS ...

Why does replacing <input> with <TextField> in Material-UI & React cause the form submission to fail?

Recently, I encountered an issue with my CRUD Todo app's form for adding tasks. Initially built with a basic HTML input and button setup, I decided to enhance the design using Material-UI components. After introducing <TextField> in place of th ...

Javascript/Webpack/React: encountering issues with refs in a particular library

I've encountered a peculiar issue that I've narrowed down to the simplest possible scenario. To provide concrete evidence, I have put together a reproducible repository which you can access here: https://github.com/bmeg/webpack-react-test Here&a ...

Are there any images included in the WebResponse being downloaded?

I need to download HTML efficiently in order to parse it with minimal bandwidth consumption. Here is a snippet of my code: if (!String.IsNullOrEmpty(siteAddress)) webReq = WebRequest.Create(siteAddress) WebResponse webRes ...

The absence of AudioPlayer may be responsible for the compilation failure on Vercel

Here is the latest code snippet import { useState, useEffect, useRef } from "react"; import { FaPlay, FaPause, FaForward, FaBackward } from "react-icons/fa"; export default function Player() { const [isPlaying, setIsPlaying] = useState(false); const [ ...

Combining MarkDown elements into a DIV or a custom HTML tag

I have utilized the Jeykll tool to convert mark down content into HTML. I am looking to group the following mark down elements within a div element or another custom HTML tag. Markdown #Multiple Axis {:.title} Different types of data can be vis ...

Every time I attempt to create a detail page for a table, I am consistently greeted with an error message

Error: Parse error: syntax error, unexpected '' (T_ENCAPSED_AND_WHITESPACE), expecting identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING) in /var/www/2909kher/entabell/detaljer.php on line 23 <!doctype ...

Which HTML/CSS class should be chosen to pair with another class for compatibility with IE 6, 7, and 8?

I am struggling to create a clear div box that works seamlessly across various browsers such as Mozilla, Chrome, Opera, IE 9+, and Safari, including older versions like IE 6, 7, and 8. I have achieved success in all browsers except for IE 6, 7, and 8. To ...

Steps for switching back and forth between values within a nested object

In my application, I have developed a custom React hook called useToggles specifically for managing checkboxes and radio buttons. The implementation of this hook typically looks like the code snippet below: const useToggles = (initialValues = {}) => { ...

.Net RadioButton object

Having trouble styling my radio button. When I compile and check the code with Firebug, something unusual happens. Code snippet: <asp:RadioButton ID="selType1" GroupName="Type" runat="server" CssClass="radioB" Checked="true" /> Firebug result: & ...

Learn how to set default values for UI TextField, Select, and checkbox material fields in React using react-hook-form

Currently, I am facing an issue with assigning default values to a form that utilizes material UI and react-hook-form for managing the form. The problem lies in the fact that select fields do not get assigned values, and even when they do, the labels of Te ...

Expanding TypographyProps and TextFieldProps for enhanced functionality

Currently, I am developing a React component using TypeScript along with Material UI (MUI). The main purpose of this component is to display either an input field or text based on the mode selected. To switch between these modes, the prop mode is utilize ...

issue arising from integrating material-ui components with code in a react javascript application

Struggling with integrating code and material-ui components in react jsx, I encountered an issue. Here's the problematic snippet: const icols = 0; const makeTableRow = ( x, i, formColumns, handleRemove, handleSelect) => <TableRow key ...

Is it possible to use D3 for DOM manipulation instead of jQuery?

After experimenting with d3 recently, I noticed some similarities with jquery. Is it feasible to substitute d3 for jquery in terms of general dom management? This isn't a comparison question per se, but I'd appreciate insights on when it might b ...

Executing an on-click event on a button in PHP

I've been developing a learning site that involves teachers, students, and different subjects. To organize the registration process, I decided to separate the teacher and student registration pages since they input data into different tables in the da ...