Reputation: 25
I am having a hard time figuring how to switch images inside react. I need the image to switch when I hover over a certain area. The area detection was created by someone else but I am been able to place my first image as the default. But I need to figure out how to change the image when I hover over the area.
This is what the images are imported as
import suitcase_open from '../images/suitcase_openEMPTY.png';
import box_open from '../images/discardbox_open.png';
import suitcase_closed from '../images/suitcase_closed.png';
import box_closed from '../images/discardbox_closed.png';
These are the two divs where I need to change the image
<div className='bound bound0'>
<img
id = 'box'
src = {box_closed}
/>
</div>
<span id='discard'>discard</span>
<div className='bound bound1' >
<img id = 'suitcase' src = {suitcase_closed} />
</div>
<span id='keep'>keep</span>
I was thinking about using onMouseOver but I do not know how to implement the change for the image source. I need to change from the closed to open versions.
Upvotes: 0
Views: 234
Reputation: 16576
You will likely need some state to track whether the suitcase is open or closed. You can then use a ternary operator to display the right image. The following code assumes you might also want to set it back to closed when mousing out.
function App() {
const [open, setOpen] = useState(false);
return (
<img
id='suitcase'
src={open ? suitcase_open : suitcase_closed}
onMouseOver={() => setOpen(true)}
onMouseOut={() => setOpen(false)}
/>
)
}
Upvotes: 1