ResponsiveBackgroundImage

Overview

The ResponsiveBackgroundImage component is designed to help you use background images efficiently. It takes care of image-set CSS function for you.

📘

The ResponsiveBackgroundImage component renders a div behind the scenes, with the image attached to it via CSS. With that in mind, you might want to use ResponsiveImage instead.

Import

The ResponsiveBackgroundImage component can be imported directly from the frontend-ui package, which is pre-installed in your Shogun Frontend store.

import ResponsiveBackgroundImage from 'frontend-ui/ResponsiveBackgroundImage'

Usage

import React from 'react'
import getResponsiveImageSrc from 'frontend-ui/getResponsiveImageSrc'
import ResponsiveBackgroundImage from 'frontend-ui/ResponsiveBackgroundImage'

const MyComponent = ({ src }) => {
  // Assuming `src` is: https://f.shgcdn.com/cbc7d039-b532-42d4-979a-2c8180befadd/ 
  return (
    <ResponsiveBackgroundImage
      srcs={{
        '(max-width: 768px)': getResponsiveImageSrc(src, { width: '800' }),
        '(min-width: 768px) and (max-width: 1024px)': getResponsiveImageSrc(src, {
          width: '1000',
        }),
        default: getResponsiveImageSrc(src, { width: '1200' }),
      }}
      alt="A black t-shirt with a black Shogun logo on it. The t-shirt is on a red surface."
      style={{ width: '600px', height: '300px', backgroundSize: '100%' }}
      loading="lazy"
    />
  )
}

export default MyComponent

Here we tell the component to render three different images for three different screen resolutions, which is going to be rendered as:

/* default */
.my-img {
  background-image: url("...");
}

@media (max-width: 768px) {
  .my-img {
    background-image: url("...");
  }
}
@media (min-width: 768px) and (max-width: 1024px) {
  .my-img {
    background-image: url("...");
  }
}

📘

Note

If width and height are specified, the background image will turn responsive. We highly encourage providing them if that's your use case.

Props

name

type

default value

description

srcs

object

Accepts an object containing key-value pairs of valid media query and image urls. Any value supported by CSS @media expression is supported. You can use default as a key for top level background-image style (see an example above). This is required.

alt

string

Defines an alternative text description of the image. Recommended.

loading

eager | lazy

eager

Controls when the image is loaded:
eager on page loads, lazy when image is near the viewport.

width

string (example: 2560)

Sets the width of the image. Recommended to avoid layout shifting.

height

string (example: 1440)

Sets the height of the image. Recommended to avoid layout shifting.


Did this page help you?