I want to learn how to change the background image in React based on different components

Hey there! I've been learning and came across the Tomorrowland website. I really love the background scrolling effect on the homepage, where it changes depending on the component. I'm not sure how to code it myself and could really use some assistance.

import './App.css';
import Hero from './components/hero/Hero';

function App() {
  return (
    <div className="app">
      <div className="Blobs_blobs__cW0d3">
        <img src="/images/principal_bg.jpg" className="Blobs_backgroundImage__ciJQh Blobs_visible__EJ_Hc" alt="default background" />
        <img src="/images/bleu_bg.jpg" className="Blobs_backgroundImage__ciJQh" alt="Belgium background" />
        <img src="/images/blanc_bg.jpg" className="Blobs_backgroundImage__ciJQh" alt="Winter background" />
        <img src="/images/violet_bg.jpg" className="Blobs_backgroundImage__ciJQh" alt="Brasil background" />
        <img src="/images/rouge_bg.jpg" className="Blobs_backgroundImage__ciJQh" alt="Owr background" />
      </div>
      <div className='appContainer'>
        <Hero />
        <Hero />
        <Hero />
        <Hero />
        <Hero />
      </div>
    </div>
  );
}

Answer №1

Implementing a state to manage background color changes based on scroll position is essential.

Consider the following approach:

Initiate the state with an initial color, such as orange for the TL website.

const [backgroundColor, setBackgroundColor] = useState('orange');

Add a 'scroll' event listener upon mounting and remove it to prevent memory leaks.

useEffect(() => {
    window.addEventListener('scroll', handleScroll);
    return () => {
      window.removeEventListener('scroll', handleScroll);
    };
}, []);   // on mount

Create a function to update the background color state based on scroll position.

const handleScroll = () => {
    const scrollPosition = window.scrollY;
    if (scrollPosition < 100) {
      setBgColor('white');
    } else if (scrollPosition < 200) {
      setBgColor('lightblue');
    } else if (scrollPosition < 300) {
      setBgColor('lightgreen');
    } else {
      setBgColor('lightcoral');
    }
};

Apply the background color to your HTML div for styling purposes.

// Container/background div surrounding content.
<div style={{ height: '2000px', backgroundColor: backgroundColor }}>
    <div style={{ height: '200px', backgroundColor: 'black' }}>
<div style={{ height: '200px', backgroundColor: backgroundColor }}>

Wishing you success!

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

Error in Redux app: Attempting to access the 'filter' property of an undefined value

I am currently encountering an issue with my reducer: https://i.stack.imgur.com/7xiHJ.jpg Regarding the props actual, this represents the time of airplane departure or arrival, and it is a property within my API. The API structure looks like this: {"body ...

Apply a CSS filter to blur and invert the colors of the entire webpage

When using both webkit filters "blur" and "invert", only the blur effect is functioning properly. However, if the "blur" filter is removed, then the "invert" filter works as intended. As of now, only Chrome and Opera browsers are responding correctly to t ...

The following middleware is not functioning properly on a local SSL server

When I run my Nextjs app without SSL using "next dev", the middleware functions as expected without any errors. However, if I attempt to run the app with SSL enabled, an empty middleware function triggers an error. The code for the middleware function (l ...

I'm having trouble modifying the border color of a TableCell component in material-ui

I am struggling to change the border color of a table cell. Despite numerous attempts, I have been unsuccessful in my efforts. Can someone please assist me with this? const customTheme = createTheme({ overrides: { MuiTableCell: { root: { ...

Oops! Looks like there was a problem with the hook call in the Codegen, Apollo, and Next.js. Please double

Attempting to implement the signup mutation using a generated hook from Codegen: export default function signUpComponent() { const { register, handleSubmit } = useForm<SignUpFormData>(); const [signUpMutation, { data, loading, error }] = useSignU ...

Adjusting background size using jQuery as the window is resized

Exploring ways to dynamically resize the background image of my website based on the current window dimensions using jQuery. At the moment, I have tried the following approach: $(window).resize(function() { $("body").css({"background ...

Encountering a problem with withStyles in the latest release of Material-UI version

I am facing an issue with mui/material v5.0.4 and ts v4.4.4 when using the withStyles method. The error occurs when I try to use the AntSwitch component: 'AntSwitch' cannot be used as a JSX component. Its element type 'ReactElement<any, ...

Bony Scaffold - halting the motion of specific components

Currently, I am utilizing skeleton to create a fluid layout, which is functioning effectively for the most part. However, I have encountered an issue specifically with the 2 column layout on Magento at this URL: In this setup, the navigation on the left s ...

Using jquery/offset to position a div causes it to float, but it does not take

<script type="text/javascript"> $(document).ready(function () { var top = $('#rt_outer').offset().top - parseFloat($('#rt_outer').css('marginTop').replace(/auto/, 0)); $(window).scroll(function (event) { // det ...

Tips for creating a navigation system that combines both horizontal and vertical bars

Is there a way for me to have both horizontal and vertical navigation bars on my website? I am new to design and struggling to understand why my CSS isn't working properly when applied to multiple links. <body> <div class="horizontallinks" ...

Struggling to keep my image buttons aligned in a horizontal line at the center, but they keep stacking vertically instead

I'm struggling to keep a row of image buttons centered horizontally, regardless of the window size. However, when I manage to center the buttons, they end up stacking vertically instead of aligning in a single line. I've experimented with differ ...

Elevate - Adjust state based on actionable tasks

I am striving to establish a specific data flow for my project: Determine the record-id from react-router Assign this id as a state property Once this property is set, all relevant components with their own reducer and actions should retrieve data base ...

Maximizing memory efficiency in Javascript through array manipulation strategy

In the project I am working on, I maintain a history of changes. This history is stored as an array containing objects, each with two arrays as properties. When adding a new history snapshot, it appears as follows: history.push({ //new history moment ...

Create dynamic form fields in React based on JSON input

I have been attempting to generate a form based on JSON configuration. I have parsed the JSON and utilized map functions to create material UI TextField components. However, I am encountering an issue where instead of rendering the generated components, th ...

Error message: The function r is not defined - Issue with Google Sign in on React app

I have successfully implemented Google Sign In for my react app during development, but I am facing an issue with it in the production environment. The npm module that I am using for Google authentication is available at https://www.npmjs.com/package/reac ...

Having an issue with importing Firebase in React Redux. It seems like there is an error preventing me from importing Firebase successfully. Any suggestions

I'm currently working on a project where I have integrated Firebase for database and authentication purposes. However, I encountered an error while setting up my Redux store. The error message indicates that I may not be importing Firebase correctly. ...

Preventing the Last Image from Sliding on a Bootstrap 5 Carousel in a ReactJS Project

I need help with stopping the slide at the last image in a React JS project using JavaScript. I want to modify my Slider code to remove the next and prev icons, and also halt the slider when it reaches the IMG src={slider5}. Can someone guide me on how t ...

I'm having difficulty grasping how this CSS is being used

There's something strange about the way this CSS is being used, and I can't quite wrap my head around it. .tablecontainer table { ... } I'm familiar with table.tablecontainer, which indicates that the class attribute is equal to "table ...

Steps to implement the selection of multiple items from a drop-down or list on a React.js website

Hi there, I am a newcomer to the world of React JS web development. I am looking for guidance on how to implement a feature where users can select multiple cities from a drop-down or list, similar to the examples shown in image1. Once the user has made th ...

Angular renderer's setStyle method does not support the application of linear-gradient

Why won't Angular's renderer2 apply linear-gradient CSS in this code snippet? Can anyone provide insights? export class AppComponent implements OnInit { constructor(private renderer: Renderer2, private elementRef: ElementRef) {} public ngOn ...