Search code examples
javascriptcssreactjsimagefallback

Fallback CSS background image when setting style with javascript?


In regular CSS I can use this to set a fallback image incase the first image doesn't exist or failed to load:

.container {
  background-image: url(pics/img.webp), url(pics/img.png);
}

However, when I set the style in javascript (like with React), how would one achieve this?

Thank you for any help :)


Solution

  • No different than CSS

    document.body.style.backgroundImage = "url('pics/img.webp'), url('http://placekitten.com/200/300')";

    If you are styling an element in react, basic idea

    style={{  
      backgroundImage: `${bgImagePath}, ${bgFallbackPath}`,
      backgroundPosition: 'center',
      backgroundSize: 'cover',
      backgroundRepeat: 'no-repeat'
    }}