Dagger
Dagger

Reputation: 369

How do I set element to display where my mouse clicks? (React)

I have some code below which shows/hides an li element when I click on an image. The code below works as intended; however, the image I'm using fits the entire screen and currently when the li element is shown it displays on the very top left of the image. I want the li element to display exactly where I'm clicking but having difficulty figuring out how I can do that. Please advice.

GamePage.js

const GamePage = () => {
  const [isShown, setIsShown] = useState(false);

  const handleClick = () => {
    setIsShown((current) => !current);
  };

  return (
    <div className="gamepage" onClick={handleClick}>
      {isShown && (
        <ul className="menu">
          <li className="menu-item">Waldo</li>
        </ul>
      )}
      <GamePageImage />
    </div>
  );
};

GamePage.css

.gamepage {
  position: relative;
}

.menu {
  position: absolute;
  text-align: center;

  list-style-type: none;
  margin: 5px;
  padding: 0;

  border: 1px solid #3e3e3e;
  width: 100px;
}

.menu > li {
  margin: 0;

  color: white;
  background-color: #3e3e3e;
}

.menu > li:hover {
  cursor: pointer;
  background-color: #252525;
}

Upvotes: 1

Views: 1742

Answers (1)

kingkong.js
kingkong.js

Reputation: 751

The onClick fires an event, where you can get the x and y coordinates. Save that position and use it on your ul element to place it where you want it. I've added some CSS to ul which will place it exactly where you click.

const GamePage = () => {
  const [isVisible, setIsVisible] = useState(false);
  const [position, setPosition] = useState([0,0]) // State to save the position where you clicked

const  handleClick = (event) => {
        setIsVisible(current => !current)
        setPosition([event.pageX,event.pageY]) // Save the pos where you clicked
    } 

  return (
    <div className="gamepage" onClick={handleClick}>
      {isVisible&& (
        <ul className="menu" style={{
        position: "absolute",
        left: position[0],
        top: position[1],
        tranform: "translateX(-50%)",
        transform: "translateY(-50%)",
        }}>
          <li className="menu-item">Waldo</li>
        </ul>
      )}
      <GamePageImage />
    </div>
  );
};

Upvotes: 2

Related Questions