I have a React component that is basically a card with a title, and an image. Id’like the image to change on hover of the card, not of the img
element, which is what I have happening now.
I know I can do this with CSS and the background
property, but I’d rather the button stay re-useable as a component and keep accepting props rather than tying the :hover
effect to some static CSS.
Here is what I have at the moment:
export default function ExternalProfile({
title,
imageUrl,
altImageUrl,
href,
}) {
// Make sure elements exist before getting their ID
React.useEffect(() => {
let imageVar = document.getElementById("id" + title) as HTMLImageElement;
if (imageVar) {
console.log(imageVar);
}
}, []);
return (
<a
href={href}
className="card externalCard"
onMouseOver={(imageVar.src=altImageUrl)}
onMouseOut={(imageVar.src=imageUrl)}
>
<h3>{title}</h3>
<img
id={"id" + title}
className="externalImage"
src={imageUrl}
alt={title + " icon"}
/>
<img className="arrow" src="/arrow.svg" alt="Arrow" />
</a>
);
}
But this gives the error Cannot find name 'imageVar'
I know this isn’t a file naming problem, as these are most of the solutions I seem to find online, and my files are already all named with the .tsx
extension.
2
Answers
But this gives the error Type ‘string’ is not assignable to type ‘MouseEventHandler’.
instead of giving the image variables inside interpolation
try giving like this
do the same for other one too.
write a seperate functions to handle the onMouseOver and onMouseOut
and call this in onMouseOver and onMouseOut event in anchor tag.