implementing lazy loading for images within styled components

const UserBackgroundImage = styled.div`
  background: url(${(props) => props.backgroundImage}) no-repeat center center;
}

In my styling component, I have utilized a div for displaying background images. However, I am facing a flickering issue while waiting for the image to load. Is there a lazy loading solution available for styled-component's div?

Answer №1

To make sure your styled component only appears once the image is fully loaded, create a wrapper around it.

One way to achieve this is by setting up a temporary image, waiting for it to load, and then notifying the component that the image is ready to be displayed.

const BackgroundImage = styled.div`
  background: url(${(props) => props.backgroundImage}) no-repeat center center;
`;

const LazyBackgroundImage = ({ src, children }) => {
  const [isLoaded, setIsLoaded] = useState(false);

  useEffect(() => {
    const image = new Image();
    image.addEventListener('load', () => setIsLoaded(true));
    image.src = src;
  }, [src]);

  if (!isLoaded) {
    return null;
  }

  return (
    <BackgroundImage backgroundImage={src}>
      {children}
    </BackgroundImage>
  );
};

Apply the wrapper in this manner:

<LazyBackgroundImage src="path/to/your-image.jpg">
  <p>Greetings!</p>
</LazyBackgroundImage>

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

Is it possible to eliminate the default placeholder text from Safari browser?

My goal is to design a form that includes date and time input fields. The placeholder text should move up by X pixels when the user clicks on the field. While the form appears fine in Chrome, there seems to be an issue with overlapping form fields in Safa ...

Retrieve the rowid from the first column of a jqGrid row

I want the first column of my jqGrid to display the rowid number number | name | class 1 | A | acceptable 2 | B | good 3 | C | bad Alternatively, I would like to add a column like this (image) https://docs.google.com/file/d/0Bxi6bFcYZ_MgYTI1dUJCMWEtd0E/ ...

Imitate a style using jQuery without deleting other elements

This is an example of HTML code: <div id="id1" style="width:100px;background: rgb(196, 14, 14);">1</div> <div id="id2" style="margin-top:10px">2</div> to <div id="id1" style=&qu ...

Updating content with jQuery based on radio button selection

Looking for assistance with a simple jQuery code that will display different content when different radio buttons are clicked. Check out the code here. This is the HTML code: <label class="radio inline"> <input id="up_radio" type="radio" n ...

How to Use CSS to Align an Image in a Header

I'm struggling to position an image on the top right corner of my page, specifically in the header. Despite searching for help on Stack Overflow and other online resources, I can't seem to figure it out. Currently, here is what I have: https://i ...

Embed full content in iframe using bootstrap 4

Embedding an iframe of an appointment scheduling frontend on my page has been a challenge. While the width is correct, the height of the frame is too small. Despite attempting various CSS modifications, I have not been able to achieve the desired result. I ...

What is the best way to trigger an event from a child component to a parent component in

parent.component.ts public test(){ //some code..... } parent.component.html <app-child (eventfire)="test($event)"></app-child> In this scenario, the child component button is displayed within the parent component. However, there i ...

Designing a Custom Wordpress Extension and Integrating External Scripts

As I dive into the world of WordPress plugin development, I'm seeking guidance from the codex to enhance my skills. Currently, I have a basic plugin that loads a javascript file from a CDN and is supposed to display tooltips. However, I'm facing ...

Floating image positioned between two div elements

Attempting to replicate a specific design using HTML/CSS has been a challenge. I've been struggling to position an image on top of the two divs. I would greatly appreciate any assistance with the design. Here is what I have tried so far: The follo ...

Tips for retrieving middlewares from getDefaultMiddleware without triggering the deprecation warning

I have opted for a unique setup to initialize the redux store without using the configureStore method from redux-toolkit, with the intention of dynamically injecting reducers at runtime. import { createStore, combineReducers, applyMiddleware, createImm ...

The named group Wildcard (:name*) is not functioning as expected when used with $routeProvider in AngularJS version 1.0

I'm attempting to implement a wildcard (*) routing functionality in AngularJS using the code snippet below: $routeProvider.when('/something/:action/:id/:params*\/', { templateUrl : "/js/angular/views/sample/index.html", controlle ...

The positioning and floating of two divs are set to fixed without using percentage width, however, the functionality is not

Apologies for my poor English writing :) I am attempting to float two divs side by side in a fixed position, without using percentages. This code works well on most browsers but is not compatible with IE 6. HTML <div class="right"></div> < ...

Determine the amount of time that can be allocated based on the attributes contained within the object

I am faced with a JSON structure like the one below: var meetings = [ { id: '1', start_time: "2020-11-15T08:30:00+00:00", end_time: "2020-11-15T14:15:00+00:00" }, { id: '2', start_time: &quo ...

Authentication for file uploads in Angular 2 using Dropzone and passportjs

I am currently working on implementing authentication for an admin user using Express, Passport, and MySQL in a specific page. The authentication process works fine, but I am facing an issue with verifying whether the user is logged in while uploading file ...

What is the best way to attach a button to a mat-drawer?

I am facing an issue with aligning a button to a mat drawer located to the right of the screen to ensure a clear overall design. Check out this example How can I achieve this alignment? My current approach involves placing the button inside the drawer an ...

What is the best way to create a div that maintains a consistent size while displaying images inside?

Struggling with a project and attempting to create a fixed div container for uniform picture sizes, I've tested various methods recommended by others but have had zero success in altering the size of my div container. Could it be due to my use of boot ...

Show the JSON data returned

Looking for a way to display the JSON response in a JSP page using AJAX... function doAjaxPost() { var name = $('#name').val(); var password = $('#password').val(); var gender = $('#gender').val(); var abo ...

How can I handle a 404 error if an object is not found in a JSON file?

Below is my code snippet where I check for the correct req.path and display specific text. However, I now need to show a 404 not found error message. I attempted placing it inside the for loop condition with break;, but it's not quite working as expe ...

Enhance Your Button with CSS3 Animation

While experimenting with CSS3 animations, I encountered a challenge when trying to apply an animation to a button upon clicking. The desired effect was for the button to zoom in, spin, and then zoom out, giving the appearance of flying off the screen. Surp ...

What is the process for changing and updating the key of an object based on comparisons with other objects?

My task involves working with an array of objects that contain unique IDs as keys. const sampleObj1 = {0011:[{},{}], 0022:[{}, {}], 0033:[{},{}]} const sampleObj2 = [{id:0011, name:'test1'}, {id:0022, name:'test2'}, {id:0033, name:&apos ...