Home > AI > Frontend > ReactJS >

backgroundImage

Example 1: using external URL

function App() {
  return (
    <div style={{ 
      backgroundImage: `url("https://images.unsplash.com/photo-1612024796093-e2323494011c?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=1267&q=80")` 
    }}>
      Hello World
    </div>
  );
}

Example 2: using /src Folder

import bg from "./imgs/bg.png";

const { v4: uuidv4 } = require('uuid');


function App() {
  return (
    <div style={{ backgroundImage: `url(${bg})` }}>
      Hello World
    </div>
  );
}

Example 3: using /public folder (relative path)

function App() {
  return (
    <div style={{ 
      backgroundImage: "url(/assets/images/1.jpg)" 
    }}>
      Hello World
    </div>
  )
}

Example 4: using /public folder (absolute path)

function App() {
  return (
    <div style={{ 
      backgroundImage: `url(${process.env.PUBLIC_URL + '/assets/images/1.jpg'})` 
    }}>
      Hello World
    </div>
  )
}

Example 5: setting up other properties

function App() {
  return (
    <div style={{ 
      backgroundImage: `url(${process.env.PUBLIC_URL + '/assets/images/1.jpg'})` ,
      backgroundRepeat: 'no-repeat',
      width:'250px' , 
      height: '250px'
    }}>
      Hello World
    </div>
  )
}

Leave a Reply