Lina Basuni
Lina Basuni

Reputation: 77

can't set backgroundImage in react?

Hey Guys I'm trying to build my portfolio site , I want to make the main page of the portfolio have a back ground image and when I navigate to other parts of the portfolio the background is just color , I handled setting the backgroundColor successfully but can't do the backgrounImage correctly . Here is my code.

  componentDidMount(){
      this.props.changePage("Main Page");
      document.body.style.backgroundImage="url('background.jpg')";
  }

that's the code inside the main page component but there seems to be something wrong , is it a problem with the syntax itself or the approach itself is wrong ?

EDIT 1!!

that's the code I used for backgroundColor and it's working why isn't it working with the backgroundImage .

  componentDidMount(){
      this.props.changePage("About Me");
      document.body.style.backgroundColor='black';
  }

Upvotes: 0

Views: 3526

Answers (2)

Ross Allen
Ross Allen

Reputation: 44880

Your background image is in the wrong directory for create-react-app. Move ./src/background.jpg to ./public/background.jpg.

Upvotes: 1

Hadi Mir
Hadi Mir

Reputation: 5133

Set the className of element where you want to display your image equal to .bgImage.In CSS file(named as App.css) write down the code as given below that targets .bgImage and sets its background to the URL or Path provided and import the CSS file in your main file using import './App.css';

.bgImage {
  background: url(./media/hero.jpg) no-repeat center center;
  //some other properties 
}

Upvotes: 1

Related Questions