Home > front end >  How do we set the background image to a div in react?
How do we set the background image to a div in react?

Time:09-29

i have a images folder which has 2 images. Please refer the following code App.js code

import "./styles.css";
import nf_logo from "./images/netflix_logo.png";
import nf_bg from "./images/netflix_bg.jpg";

const divStyle = {
  backgroundImage: `url(${nf_logo})`
};
export default function App() {
  return (
    <div className="App">
      <div style={divStyle}></div>
    </div>
  );
}

CodePudding user response:

You need to set the width and height of the div, or at least set those properties high and wide enough so you can see the image.

function Example() {

  const divStyle = {
    width: '150px',
    height: '150px',
    backgroundImage: `url(https://dummyimage.com/150x150/000/fff)`
  };

  return (
    <div style={divStyle} />
  );
};

// Render it
ReactDOM.render(
  <Example />,
  document.getElementById("react")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>

If your div is larger than your div just set the backgroundRepeat property to `no-repeat'.

function Example() {

  const divStyle = {
    width: '250px',
    height: '250px',
    backgroundImage: `url(https://dummyimage.com/150x150/000/fff)`,
    backgroundRepeat: 'no-repeat'
  };

  return (
    <div style={divStyle} />
  );
};

// Render it
ReactDOM.render(
  <Example />,
  document.getElementById("react")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>

CodePudding user response:

I usually import the image at the top of my component from the file system and then assign it to the component that needs it as background:

    import React from 'react';
    import backgroundImage from './some/local/place.png'

    export const Header = () => (
        <container style={{ backgroundImage: `linear-gradient(176.27deg, rgba(7, 7, 7, 0.35) 3.06%, #070707 74.05%), url( ${ backgroundImage } )` }}>
            {otherComponentsAndStuff}
        </container>
);
  • Related