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
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:
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:
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.