Home > Mobile >  React changing background images using getElementById
React changing background images using getElementById

Time:08-12

There is soemthing weird happening with me in react for some reason changing the background image of a div like that works:

document.getElementById("player1-card1").style.backgroundImage =
 `url(${require(../images/3.png)})`

But like that wont work

const y = 3
const x = `../images/${y}.png`
document.getElementById("player1-card1").style.backgroundImage =
 `url(${require(x)})`

x is the same value as ../images/3.png so why it is not working I am confused

CodePudding user response:

You shouldn't be using document.getElementById in React. If you want to set the style in react, import the image and then just pass it into the style prop.

import img from "../images/3.png"

<div style={{backgroundImage: img}}

CodePudding user response:

I don't remember how websockets api looks like, but your code should utilize state like that:

const Component = () => {
  const [image, setImage] = useState();
  useEffect(() => {
    socket.onMessage = (data) => {
      setImage(data)
    }
  })
  return <div style={{ backgroundImage: image }} />
}
  • Related