Cattttt
Cattttt

Reputation: 51

Change background-image using React Hook

I'm new to React and I'm using React Hook to build my web app. I want to change the background image of a class, so that if the width of window < 376px it will display the "backgorund_mobile" and when it larger than 376px it will display the "backgound_desktop" but it doesn't work. How can I do that? Please help me. Thank you.

Here is my code:

Header.jsx

import React from "react"; 
import backgound_desktop from '../images/desktop/image-hero.jpg';

function Header(){
return(
    <div className="heading" style={{backgroundImage: "url(" + backgound_desktop + ")"}}>
        //Some other codes
    </div>
)}
export default Header;

App.jsx

import React from "react";
import Header from "./Header";
import backgound_desktop from '../images/desktop/image-hero.jpg';
import backgorund_mobile from "../images/mobile/image-hero.jpg";

function App() {

  const [windowWidth, setWindowWidth] = React.useState(window.innerWidth);

  React.useEffect(() => {
    const handleWindowResize = () => {
      setWindowWidth(window.innerWidth);
    }
    window.addEventListener('resize', handleWindowResize);
    return () => {
      window.removeEventListener('resize', handleWindowResize);
    }
  }, []);
  if (windowWidth < 376) {
    document.querySelector("heading").style.backgroundImage = "url(" + backgorund_mobile + ")";
  };
  return (
    <div className = "container-fluid nopadding" >
    <Header / >
    </div>
  )
}

export default App;

Upvotes: 1

Views: 1026

Answers (1)

Md.Usman Ansari
Md.Usman Ansari

Reputation: 149

try it

import React, {useState} from "react"; 
import backgound_desktop from './images/images-desk.webp';
import backgound_mobile from './images/images-phone.webp';

function Header(){

const [isMobile, setMobile] = useState(false) ;

    React.useEffect(() => {
        const handleWindowResize = () => {
            const bool =  window.innerWidth < 367 ? true : false;
            setMobile(bool) 
                
        }
        window.addEventListener('resize', handleWindowResize);
        return () => {
        window.removeEventListener('resize', handleWindowResize);
        }
    }, []);

    return(
        <div className="heading" style={{backgroundImage: "url(" +( isMobile? backgound_mobile : backgound_desktop) + ")", height: '400px'}}>
            //Some other codes
        </div>
    )

}


export default Header;

Upvotes: 1

Related Questions