Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change the background image dynamically

I would like to modify the image in the background with the help of a comment.

The images come from the tmdb API. So I think you have to create a background image component and pass it on to the URL.

I know that CSS has the background-image property, but it works for static images ...

What is the best method, I would like to make this component reusable.

like image 747
FoxaLiveJS Avatar asked Nov 05 '25 14:11

FoxaLiveJS


2 Answers

Here is how you would have to do it.

  1. Create your <div> and its style with a default background-image
  2. Create 3 <button> to triggers your function changeImage() and provide a parameter
  3. Change the style.backgroundImage with JavaScript such as below:

function changeImage(category){
  document.getElementById('div-bg').style.backgroundImage = 'url("https://source.unsplash.com/320x240/?' + category + '")';
}
#div-bg {
  display: block;
  width: 320px;
  height: 240px;
  background-image: url("https://source.unsplash.com/320x240/?sky");
}
<div id="div-bg"></div>

<button onclick="changeImage('nature')">Nature</button>
<button onclick="changeImage('animal')">Animal</button>
<button onclick="changeImage('fire')">Fire</button>

If you have any question, please ask!

like image 149
Jonathan Gagne Avatar answered Nov 07 '25 03:11

Jonathan Gagne


By doing this it works, I have my background. But I did not manage to do it with a reusable component

import React from 'react';

  const VideoDetail = ({ title, description, background }) => {

  const IMAGE_BASE_URL = "https://image.tmdb.org/t/p/w500/";

  const backgroundStyle = {
    color: 'white',
    backgroundRepeat: 'no-repeat',
    backgroundAttachment: 'scroll',
    backgroundPosition: 'center',
    backgroundSize: 'cover',
    width: "100%",
    height: "400px",
    backgroundImage: `url(${IMAGE_BASE_URL}${background})`
 };

 return(
    <div>
      <div style={background !== undefined ? backgroundStyle : null }>
        <h1>{title}</h1>
        <p>{description}</p>
      </div>
  </div>
  )
} 
export default VideoDetail;import React from 'react';
like image 26
FoxaLiveJS Avatar answered Nov 07 '25 03:11

FoxaLiveJS



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!