3

here am getting an image from props, I have to make that image as a background image for a particular element. I achieved this using styled-components. But in my app, we are not using styled components anywhere, so I am trying to achieve this using inline styles. Because it's dynamic we couldn't or may not be able to pass this image to the CSS file.

this is my method using styled-components, anyway to change this using inline styles, please help me with that, Thanks

Styled Components

const BannerImage = styled.div`
  &::after {
    background: url(${(props) => props.image}) no-repeat;
    content: '';
    background-size: cover !important;
    background-position: center center !important;
    right: 0;
    height: 100%;
    position: absolute;
    left: 0;
  }
  @media (min-width: 992px) {
    &::after {
      right: calc((-1%) - ((100vw - 992px) / 2));
    }
  }
`;

Element used styled component

<BannerImage
      image={image}
      className="col-lg-6 col-md-16 col-sm-12 col-12 h-100 d-flex"
 />

SDK
  • 1,356
  • 3
  • 19
  • 44

2 Answers2

1

While you can't directly style a pseudo element with inline styling you can set a CSS variable. Could you use that as a way to pass the background image url?

e.g.

   const myElement = document.querySelector('.myElement');
    myElement.style.setProperty('--bgurl', 'URL(' + the URL + ')');

and in the CSS

.myElement::after {
  background-image: --bgurl;
}
A Haworth
  • 30,908
  • 4
  • 11
  • 14
0

For simple styles like background color, color, etc, you can use inline style directly without any library.

But for pseudo-class, pseudo-element, and media query, you have to use a library to implement inline styling.

There is a library called Radium https://github.com/FormidableLabs/radium to help that in React.

Jabal Logian
  • 1,666
  • 4
  • 24
  • 46