skip to Main Content

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


  1. <a
          href={href}
          className="card externalCard"
          onMouseOver={(imageVar.src = `${altImageUrl}`)}
          onMouseOut={(imageVar.src = `${imageUrl}`)}
        >
    

    But this gives the error Type ‘string’ is not assignable to type ‘MouseEventHandler’.

    instead of giving the image variables inside interpolation

     onMouseOver={(imageVar.src=`${altImageUrl}`)}
    

    try giving like this

    onMouseOver={(imageVar.src=altImageUrl)}
    

    do the same for other one too.

    Login or Signup to reply.
  2. write a seperate functions to handle the onMouseOver and onMouseOut

     const handleMouseOver = (event) => {
              event.target.src = altImageUrl; 
        };
            
     const handleMouseOut = (event) => {
              event.target.src = imageUrl; 
        };
    

    and call this in onMouseOver and onMouseOut event in anchor tag.

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