I want to show different image on hover of div in react with usestate. Issue is when i hover on single image then all images changed. How to handle this issue. Screenshots of hover result are attached
const [open, setOpen] = useState(false);
<div className="container-fluid" id="companies">
<div className="row">
<div className="col-md-3 p-0">
<div className="company-block" onMouseOver={() => setOpen(true)} onm ouseOut={() => setOpen(false)}>
<Image src={open ? BlockFiBlack : BlockFiWhite}/>
</div>
</div>
<div className="col-md-3 p-0">
<div className="company-block" onMouseOver={() => setOpen(true)} onm ouseOut={() => setOpen(false)}>
<Image src={open ? NerdWalletBlack : NerdWalletWhite}/>
</div>
</div>
<div className="col-md-3 p-0">
<div className="company-block" onMouseOver={() => setOpen(true)} onm ouseOut={() => setOpen(false)}>
<Image src={open ? SuperRateBlack : SuperRateWhite}/>
</div>
</div>
<div className="col-md-3 p-0">
<div className="company-block" onMouseOver={() => setOpen(true)} onm ouseOut={() => setOpen(false)}>
<Image src={open ? XealBlack : XealWhite}/>
</div>
</div>
</div>
</div>
Before div hover result After div hover result
CodePudding user response:
move individual items like following to separate component
<div className="col-md-3 p-0">
<div className="company-block" onMouseOver={() => setOpen(true)} onm ouseOut={() => setOpen(false)}>
<Image src={open ? BlockFiBlack : BlockFiWhite}/>
</div>
</div>
and manage open state there.
this would work fine that way.
CodePudding user response:
You can use a string instead of a boolean to set which image is currently hovered.
const [open, setOpen] = useState('');
const unhover = () => {
setOpen('')
}
<div className="container-fluid" id="companies">
<div className="row">
<div className="col-md-3 p-0">
<div className="company-block" onMouseOver={() => setOpen('blockfi')} onm ouseOut={unhover}>
<Image src={open === 'blockfi' ? BlockFiBlack : BlockFiWhite}/>
</div>
</div>
<div className="col-md-3 p-0">
<div className="company-block" onMouseOver={() => setOpen('nerdwallet')} onm ouseOut={unhover}>
<Image src={open === 'nerdwallet' ? NerdWalletBlack : NerdWalletWhite}/>
</div>
</div>
<div className="col-md-3 p-0">
<div className="company-block" onMouseOver={() => setOpen('superrate')} onm ouseOut={unhover}>
<Image src={open === 'superrate' ? SuperRateBlack : SuperRateWhite}/>
</div>
</div>
<div className="col-md-3 p-0">
<div className="company-block" onMouseOver={() => setOpen('xeal')} onm ouseOut={unhover}>
<Image src={open === 'xeal' ? XealBlack : XealWhite}/>
</div>
</div>
</div>
</div>