Karim Abou El Naga
Karim Abou El Naga

Reputation: 121

Set background image for one component differently in ReactJS

I am struggling with a problem, where I want to set the background image for one component differently. This is how it is written in the index.css:

body,
html {
  margin: 0;
  padding: 0;
  height: 100%;
  width: 100%;
  background-position: center;
  background-size: cover;
  background-repeat: no-repeat;
  font-family: "EB Garamond", serif !important;
  background-image: url("views/graphics/CatanBG.png");
  overflow-x: hidden;
}

/* set background image per page */
.game-bg {
  background: url('views/graphics/sea.gif');
  background-size: 30px;
 ;
}

This produces the following picture:

Board

As you can see, the actual background image is still ("views/graphics/CatanBG.png") and when zooming out it looks like this:

enter image description here

I use game-bg in the div for the component where I want to have it as background image like that:

render() {
    console.log("state", this.state);
    return (
      <div className={"game-bg"}>
       more code
      </div>
}

Anyone with an idea on what the problem is?

Thanks in advance!

Upvotes: 0

Views: 848

Answers (2)

Pooriya A
Pooriya A

Reputation: 1

first import your image url, for example: import background from '../pics/background1.png' then you can use useEffect to change style for body when this component will be rendered:

useEffect(() => {document.body.style.backgroundImage = `url(${background})`})

Upvotes: 0

Red Baron
Red Baron

Reputation: 7642

so I know you're using CSS instead but if you wanted to consider using styled-components (which is great by the way) then it's super simple. You can use this:

const GlobalStyle = createGlobalStyle`
  html {
    background: ${props => (props.something ? url(imageone) : url(imagetwo))};
  }
`

that way you can pass a prop in and then render something different based off that. I do this to render a different background image for my app

the docs are here: https://styled-components.com/docs/api

let me know if you need any more details

Upvotes: 1

Related Questions