Search code examples
reactjsmedia-queriesinline

React Inline BackgroundImage with Media Queries


I am working on a react app that is responsive. When the viewport shrinks or increases the 'backgroundImage' should change. I used an inline style because I was unable to use a relative path to the image which is in the public folder.

I have created a media queries within a variable in react with the widths that they should change.

I have placed the style within the .hearder-flex dive element.

Header.js

const Header = () => {

    const media = {
        '@media (max-width: 650px)':{
            backgroundImage: 'url("starter-code/assets/mobile/bg-pattern-header.svg")' ,
        },
        '@media (min-width: 750px)':{
            backgroundImage: 'url("starter-code/assets/tablet/bg-pattern-header.svg")' ,
        }
    }

    

    return ( 
        <div className="header-wrapper">
            <main className="header-flex" style={media}>
                    <img src="starter-code/assets/desktop/logo.svg" alt="logo" className="logo-img"/>
                    <div class="space-around">
                        <img src="starter-code/assets/desktop/icon-sun.svg" alt="icon-sun" className="sun-img"/>
                        <label className="switch">
                            <input type="checkbox" />
                            <span className="slider"/>
                        </label>
                        <img src="starter-code/assets/desktop/icon-moon.svg" alt="icon-moon" className="moon-img"/>
                    </div>
            </main>
                <div className="input-search">
                    <img src="starter-code/assets/desktop/icon-search.svg" alt="icon-search" className="icon-search"/>
                    <input type="text" placeholder="Enter desired job..." className="enter-job"/>
                </div>

        </div>
     );
}
 
export default Header;

Solution

  • well, Media Queries cannot be used as the inline style.

    However you can use this approach to assign the background images:

    First create the css style as below and save it in a variable called css:

    const css = `@media (max-width: 650px) {
        .backimage {
            background-image: url("https://picsum.photos/200/300")
        }
    }
    @media (min-width: 750px) {
        .backimage {
            background-image: url("https://picsum.photos/200");
        }
    }`;
    

    Then, use it in the component in the style tag above the main tag:

    <style scoped>{css}</style>
    <main style={{ height: 300 }} className="backimage">
    

    Please also check this sandbox link