Display a pop-up when hovering over a layer with react-leaflet

I am attempting to display a popup when hovering over a layer in react leaflet. Utilizing GeoJson to render all layers on the map and onEachFeature() to trigger the popup on hover, I encountered an issue where the popup only appeared upon click, not hover. Below is the code snippet along with my map showing layers colored in blue.

import { MapContainer, TileLayer, Marker, Popup, GeoJSON } from 'react-leaflet';
import './index.css'
import React, { useEffect, useState } from 'react';
import "leaflet/dist/leaflet.css";
import Header from '../common/header'
import { PixiOverlay } from 'react-leaflet-pixi-overlay';
import * as polygonData from '../../data/tinh.json';
import axios from 'axios'
import * as Request from '../../services';

export default function Home() {
  // const [display, setDisplay]=useState(false);
  // const [options, setOptions]=useState([]);
  // const [search, setSearch]= useState("");

  //function to show popup when hover
  const onEachContry = (feature, layer) =>{
    const contryName = feature.properties.NAME_1;   
    layer.on('mouseover', function (e) {
      layer.bindPopup(contryName)
    });
  }

  return (
    <>
      <Header />
      <MapContainer center={[10.7743, 106.6669]} zoom={5}>
        <TileLayer
          attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
          url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
        />
        <GeoJSON
          data={polygonData.features}
          onEachFeature={onEachContry}
       />
      </MapContainer>
</>

https://i.sstatic.net/9c88X.jpg

https://i.sstatic.net/gGBEf.jpg

Answer №1

To make the popup appear when you hover, all you need to do is call the openPopup() method.

//function to display popup on hover
const displayPopup = (feature, layer) =>{
  const countryName = feature.properties.NAME_1;   
  layer.on('mouseover', function (e) {
    layer.bindPopup(countryName).openPopup(); // include openPopup() here
  });
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to retrieve the current URL in Next.js without relying on window.location.href or React Router

Is there a way to fetch the current URL in Next.js without relying on window.location.href or React Router? const parse = require("url-parse"); parse("hostname", {}); console.log(parse.href); ...

Loading a series of images in advance using jQuery

I have a series of frames in an animation, with file names like: frame-1.jpg, frame-2.jpg, and I have a total of 400 images. My goal is to preload all 400 images before the animation begins. Usually, when preloading images, I use the following method: v ...

What is the best way to retrieve an ID when parsing JSON recursively?

Could you provide guidance on how to retrieve the IDs of all children when parsing JSON data? I have attempted to use a recursive function, but it seems to be calling infinitely. For reference, here is my code snippet: http://jsfiddle.net/Ds8vQ/ for(var ...

Looking to set up a layout with two columns in the first row and one column in the second row, then combine the two columns using HTML and CSS

My goal is to set up a layout with two columns in the first row, one at 70% width and the other at 30%, and a single column in the second row. However, when I add text and images, the content doesn't position as expected: body { background-image: ...

Issue with reactivity in deeply nested objects not functioning as expected

Currently, I am utilizing Konvajs for my project. In simple terms, Konvajs provides a canvas for drawing and editing elements such as text nodes that can be manipulated by dragging and dropping. These nodes are organized within groups, which are then added ...

What could be the reason for the ReferenceError that is being thrown in this code, indicating that '

let number = 1; console.log(number); Feel free to execute this basic code snippet. You may encounter an issue: ReferenceError: test is not defined, even though the variable was declared. What could be causing this unexpected behavior? ...

What is the most effective method for filtering a table using both column-specific and global filters?

Looking for the most efficient way to filter a large chunk of JSON data client-side using a table? Each header has an input filter where users can enter a string to filter that specific property. There is also a global filter for free text search. If you ...

What are the methods for providing both successful and unsuccessful promises, with or without data?

Seeking guidance on how to return a promise and an object named output before or after the $http call in AngularJS, specifically using Typescript. How can I ensure it works correctly? topicNewSubmit = (): ng.IPromise<any> => { var self = t ...

Using an object does not result in updated data, while data changes are typically observed when using a variable

In the process of developing a function to update a custom checkbox upon clicking (without resorting to using the native checkbox for specific reasons). Here's the code snippet for the checkbox: <div class="tick-box" :class="{ tick: isTicked }" @ ...

Displaying and hiding the Angular <object> element

I am faced with a challenge involving managing files of various formats and creating a gallery with preview functionality. Everything works smoothly when clicking through items of the same format, like JPEGs. However, an issue arises when switching from vi ...

Utilizing useNavigate in React Router Dom v6 for Redirecting to Specific Path based on Login Status

A scenario where the navigation is passed from login to useFirebase let navigate = useNavigate(); const handleLoginSubmit = (e) => { loginUser(loginData.email, loginData.password, navigate); e.preventDefault(); // alert('Lo ...

Utilize JavaScript destructuring to assign values to a fresh object

When working with JavaScript/Typescript code, what is a concise way to destructure an object and then assign selected properties to a new object? const data: MyData = { x: 1, y: 2, z: 3, p: 4, q: 5 } // Destructuring const { x, z, q } = data; // New O ...

What is the method of duplicating an array using the array.push() function while ensuring no duplicate key values are

In the process of developing a food cart feature, I encountered an issue with my Array type cart and object products. Whenever I add a new product with a different value for a similar key, it ends up overwriting the existing values for all products in the ...

Styling emails in an inbox with CSS

I am developing an email application and aiming for the inbox layout to be similar to that of Mac Mail. The emails are fetched from a database using ajax, outputting to XML. I then loop through the entries to extract the necessary elements. My concern li ...

An illustration of a skeleton alongside written content in neighboring sections

I am relatively new to CSS and came across an issue with Skeleton when resizing the browser window. I have an image and text displayed next to each other in columns, as shown below (although there is much more text in reality). Everything looks fine initia ...

The icons in webviews on mobile apps (iOS and Android) fail to render correctly

My font icons are behaving inconsistently on webkit-based mobile browsers when used on mobile devices. When hovering over the span on a desktop browser, the icon properly fills its container: https://i.sstatic.net/qzrmz.png However, when hovering over t ...

Ways to change the CSS styles of components within App

When my app is in full screen mode, I need to increase the font size for certain components. Within my App.jsx file, I have a variable that adds the "fullscreen" class to the root DIV of the app when triggered. Instead of using a blanket approach like * ...

Locate a deeply nested element within an array of objects using a specific string identifier

Trying to search for an object in an array with a matching value as a string can be achieved with the following code snippet. Is there an alternative method to optimize this process without utilizing map? Code: const arr = [{ label: 'A', ...

js simulate a click on an anchor element based on the child element's id

I am trying to automatically trigger a click on an a tag that contains a div with the id='a'. $(document).ready(function() { $("#chat_list_content a:has(div[id='a'])").click(); //$("#chat_list_content a:has(div[id='a']) ...

Loss of data in the local storage when the page is reloaded

click here to see image I have managed to save data to local Storage successfully, but it keeps disappearing when I reload the page. Can someone guide me on how to handle this issue? I am new to this and would greatly appreciate any help. Thank you. https ...