skip to Main Content

I wrote this codes for changing background image according to user’s selected. But The background image neither loads nor changes Please help me, I can not develope my own project.

const [selectedBgImg,setSelectedBgImg] = useState('../images/forestBg.jpg');
return(
<div className={`flex min-h-screen flex-col items-center z-50  bg-cover`} style={{'backgroundImage': `url(${selectedBgImg})`}}>
    <select value={selectedBgImg} className='cursor-pointer' name="selectedBg"  onChange={(e)=>{setSelectedBgImg(e.target.value)}}>
                <option value="../images/forestBg.jpg">Forest</option>
                <option value="../images/seaBg.jpg">Sea</option>
                <option value="../images/libraryBg.jpg">Library</option>
              </select>
</div>)

2

Answers


  1. You should use the absolute path or the correct relative path based on the location of your component. Assuming that the images folder is in the same directory as your component,

    You can try using the following code:

    const [selectedBgImg, setSelectedBgImg] = useState('/images/forestBg.jpg');
    
    return (
      <div className={`flex min-h-screen flex-col items-center z-50 bg-cover`} style={{ 'backgroundImage': `url(${selectedBgImg})` }}>
        <select value={selectedBgImg} className='cursor-pointer' name="selectedBg" onChange={(e) => { setSelectedBgImg(e.target.value) }}>
          <option value="/images/forestBg.jpg">Forest</option>
          <option value="/images/seaBg.jpg">Sea</option>
          <option value="/images/libraryBg.jpg">Library</option>
        </select>
      </div>
    )
    
    Login or Signup to reply.
  2. While using the image paths if it not loading properly, use require in front as the correct image path would not be recognized properly without using that. So you can try this code:

    const [selectedBgImg,setSelectedBgImg] = useState(require('../images/forestBg.jpg'));
    return(
    <div className={`flex min-h-screen flex-col items-center z-50  bg-cover`} style={{'backgroundImage': `url(${selectedBgImg})`}}>
        <select value={selectedBgImg} className='cursor-pointer' name="selectedBg"  onChange={(e)=>{setSelectedBgImg(e.target.value)}}>
                    <option value={require("../images/forestBg.jpg")}>Forest</option>
                    <option value={require("../images/seaBg.jpg")}>Sea</option>
                    <option value={require("../images/libraryBg.jpg")}>Library</option>
                  </select>
    </div>)
    

    Make sure you need to use require while setting the default value of the usestate. Otherwise while loading the first time, the background image may not appear.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search