skip to Main Content

I want to display a menu if the cursor is on an image, and the the menu is leaving if the cursor is not on the menu or the image

heres what i tried to do but it doesnt work, in menu theres my menu list
i also tried to put everything in the same component but its not working

import "../styles/Background.css";
import Menu from './Menu'
import { useState } from "react";
import skull from '../assets/bg3.gif'

  
  function Background () {
    const title = "Blog"
    const title_header = "True Crime Story"
    const[showMenu,setShowMenu] = useState(false)
   

  return (
    <div className="body">
        <div className="modal">
            <div className="modal-content">
                <title>{title}</title>
                <div className="main-title">
                    <h1>{title_header}</h1>
                </div>
                <p>Latin text</p>
            </div>
        </div>
        <img src={skull} className="image" onMouseOver={()=>setShowMenu(true)}/>
        {showMenu ? <Menu/> : null}
    </div>
  )
}

export default Background

2

Answers


  1. Depending your use case, you can handle this either with pure CSS or with state.

    With CSS (give a className to the menu <div>):

    /* when .image is hovered inside .body, set display to .menu */
    
    body:has(.image:hover) .menu {
      display: block;
    }
    .menu {
      display: none;
    }
    

    With state:

    function Background() {
      const title = "Blog"
      const title_header = "True Crime Story"
      const [showMenu, setShowMenu] = useState(false)
    
      const handleMouseOver = () => {
        setShowMenu(true)
      }
    
      const handleMouseLeave = () => {
        setShowMenu(false)
      }
    
      return (
        <div className="body">
          <div className="modal">
            <div className="modal-content">
              <title>{title}</title>
              <div className="main-title">
                <h1>{title_header}</h1>
              </div>
              <p>Latin text</p>
            </div>
          </div>
          <img src={scull} className="image" onMouseOver={handleMouseOver} onMouseLeave={handleMouseLeave} />
          {showMenu ? <div className="menu">ezbdb</div> : null}
        </div>
      )
    }
    
    Login or Signup to reply.
  2. Above answer will work.

    Additionally, adding mouse events directly to the HTML <img> tag is possible but generally not recommended. It’s better to add mouse events to a parent element that wraps the image, such as a <div> or <a> tag, for proper event handling and image-related actions.

    Hope it help 🙂

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