Tips for switching the background image in React while a page is loading?

Is there a way to automatically change the background of a page when it loads, instead of requiring a button click?

import img1 from '../images/img1.jpg';
import img2 from '../images/img2.jpg';
import img3 from '../images/img3.jpg';

const [background, setBackground] = useState(img1);

const list = [img1, img2, img3];

const css = {
    backgroundImage: `url(${background})`,
};

return (
    <div style={css}>
        <button onLoad={() => setBackground(list)}>Change background</button>
    </div>
);

However, setBackground(list)} seems to have trouble reading the array and the onLoad event does not trigger when the page is reloaded.

Any assistance would be greatly appreciated!

Answer №1

Utilizing localStorage, useEffect, and useRef is crucial for the solution. The key logic is implemented within the useEffect hook, as it handles all the necessary operations when the component mounts. Check out this working example.

  1. Start by initializing an absolute number using useRef
  2. Attempt to retrieve a value from localStorage; if it's empty, set a default value. This is also where we check the array index.
  3. The next time around, skip the check and increment the obtained value and absolute number.
  4. Finally, send the result to both state and localStorage

App.js

import { useState, useEffect, useRef } from "react";

export default function App() {
  const img1 = "https://dummyimage.com/400x200/a648a6/e3e4e8.png";
  const img2 = "https://dummyimage.com/400x200/4e49a6/e3e4e8.png";
  const img3 = "https://dummyimage.com/400x200/077d32/e3e4e8.png";

  let [lsNum, setLsNum] = useState(0);
  // Initialize an absolute number with '1'
  let count = useRef(1);

  const list = [img1, img2, img3];

  useEffect(() => {
    // Retrieve the value from localStorage and convert to a number
    const lS = Number(localStorage.getItem("image"));
    // Conditional check: If localStorage contains number 2 or more, reset it to 0
    if (lS >= 2) {
      localStorage.setItem("image", 0);
      return;
    }
    // Increment the absolute number using the value from localStorage
    count.current = count.current + lS;
    // Update the state with the result
    setLsNum(count.current);
    // Store the resulting number in localStorage
    localStorage.setItem("image", count.current);
  }, []);

  const css = {
    height: "200px",
    width: "400px",
    display: "block",
    backgroundImage: `url(${list[lsNum]})`, // dynamically change image based on index
    backgroundPosition: "center",
    backgroundSize: "cover",
    border: "1px solid red"
  };

  return (
    <div className="App">
      <div style={css}></div>
    </div>
  );
}

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

What is the best way to add a filter to a nested array?

I am currently facing a challenge in creating a multiple filter for multiple arrays without duplicating the nested array. I am working with vuejs and some plugins that are relying on the array, so my only option is to filter it without modifying it. Using ...

Is the Vue-portal enabled conditionally?

I am looking to include some additional information in the navbar (parent component) using Vue Portal. So, within a component, I can use the following code: <portal to="navbar"> <b-button>Some option</b-button> </portal&g ...

Troubleshooting Problem with Centering Rows in Bootstrap

I am utilizing the most recent version of Bootstrap 3 to design a website for a friend, but I am encountering a challenge with centering elements on the page. Typically, I would use the following code: .center{ width: 90%; margin: 0 auto; } Howev ...

Extracting command line arguments and parameters from a string within a node application for a simulated terminal interface site

In my Next.js project at this source, I have a string called command and I need to extract all the arguments (if any) and parameters (if any) into an array and object, respectively. For example: const command = "login 'username' -p 'secret ...

Efficiently Filtering User Input and Other Things

Imagine I have a setup for organizing a television guide like this: <div class="day"> <p>A Date</p> <div class="time"> <p>A Time</p> <div class="show"> <p>A Show</p> ...

Tips for updating the position on a website using AJAX

I am developing a website that pulls data from a MySQL database and showcases it on a map. How can I implement an automatic data refresh on the webpage every second? Should I incorporate my AJAX code within a timer function? Do I need to put the PHP scri ...

The execution of the 'yarn start-https' command encountered an error and exited with code 1

Struggling to set up the environment for a downloaded project. After running yarn install, yarn build, and yarn start-https, I encountered this error message: Error: error:0909006C:PEM routines:get_name:no start line at node:internal/tls/secure-context ...

Using jQuery to target multiple div elements sharing a common class that are separate from the currently selected div

I am facing a challenge with a div that has a variable number of specific children that I need to toggle between hide and show. It's difficult to explain, but the following code provides a clear example. <div class="item_content_container"> ...

Using scrollto function after history.push in React

Currently, I am utilizing history.push for routing purposes (using react-router-dom 5.3.4). The majority of the links on my menu trigger scrollTo actions. However, one link directs to /about. When attempting to use a scrollTo link from the /about page, I ...

Tips for correctly storing an async/await axios response in a variable

I am facing a challenge with the third-party API as it can only handle one query string at a time. To overcome this limitation, I am attempting to split multiple strings into an array, iterate through them, and make async/await axios calls to push each res ...

Using jQuery and JavaScript: The recursive setTimeout function I created accelerates when the tab is no longer active

I am facing a unique challenge with my jQuery slideshow plugin that I'm currently developing. Although the code is running smoothly, I have observed an issue where if I leave the site open in a tab and browse elsewhere, upon returning to the site (us ...

Calculate the total number of pages within an epub document

As a beginner in the world of epub, I have acquired numerous files in different epub formats and now wish to make them easily readable online. I'm not quite sure what an epub file contains. Is there a method to determine the number of pages in my epub ...

Tips on displaying the menu only when scrolling through the webpage

Currently, my website has a right menu that causes overlap with the content on mobile and small devices. To address this issue, I am working on hiding the right menu when the page is stable. The plan is for the menu to appear as soon as the user starts sc ...

Chained module incorporating a specialized Angular form validation directive

I've been working on incorporating an angular form validation "plugin," but I've hit a roadblock trying to utilize the directive in a child module. As a test, I'm using the HighlightDirective example. @Directive({ selector: '[highligh ...

What is the easiest way to pass a chosen value to PHP?

My goal is to dynamically display photos based on the selected album without refreshing the entire page. Here is my current script: <script type="text/javascript"> function replaceContent(divName, contentS) { document.g ...

Generating a dropdown menu in HTML using JSON entities

I am attempting to populate an HTML Select element with data retrieved from JSON. Below is a simplified version of the JSON object: {"Group1": "TestGroup1", "Group2" : "TestGroup2", "TotGroups" : "2"} To achieve this, I am using JQuery and AJAX for fetch ...

Tips for effectively utilizing an autocomplete input field with Vue that draws information from a database source

I am looking for a way to implement an autocomplete feature in my Vue application using data from a database table with over 3000 records. Here is how I am currently retrieving the data: data(){ return{ inboundRelation_Trelation_data: [], } ...

A guide on how to efficiently retrieve all images stored in a specific directory

I attempted to showcase all the images from a single directory using jQuery, but unfortunately it is not functioning as expected. My folder setup includes an 'images' folder and a 'js' folder. I followed this question on Stack Overflow ...

Slide the next section over the current section using full-page JavaScript

I'm currently developing a website utilizing the FullPage.JS script found at this link . My goal is to have the next section slide over the previous one, similar to what is demonstrated in this example. I've attempted setting the position to fix ...

Synchronize two slideshows in a cycle with timed delays between each cycle

Is there a way to add a sequential delay between slideshows in the synchronized slide show example from cycle2 API? For example, having each div.cycle-slideshow start at 5s intervals (5s, 10s, 15s, 20s...). The cycle would then repeat with the first div st ...