简体   繁体   中英

How do I create image maps (clickable areas on an image using <map >) with React and JSX?

I'm trying to create a functional component in React using hooks that will render an image with clickable areas. I've seen other posts that suggest using react-image-mapper or react-img-mapper(on-going support) but I'd like to understand how to use the useMap attribute properly in the JSX context for this problem.

The code below compiles but nothing happens when I click in the clickable area. I think I need to replace the useMap attribute in the img tag to properly link it to the map tag, but I'm stuck on how to do that. Here is the code:

    import React, {useState} from 'react';

    export const VanillaMapper = (props) => {
       const [height, setHeight] = useState(500);
       const [width, setWidth] = useState(1000);
       const [url, setUrl] = useState("https://c1.staticflickr.com/5/4052/4503898393_303cfbc9fd_b.jpg");
       const [alt, setAlt] = useState("generic");

       const handleOnClick = () => {
        console.log("You have clicked in the specified area")
    }

    return (
        <div>
            <img src={url} height={height} width={width} alt={alt} useMap="#workmap"/>
            <map name="workmap">
                <area shape="poly" coords="50,47,56,454,257,357,254,139" alt="test" onClick={()=>handleOnClick}/>
            </map>
        </div>
    )
}

Here is what got the code to work:

  1. I needed to add an href attribute to the area tag
  2. I needed to prevent the default behavior of redirecting to the href when clicking on the clickable area. To do so, I needed to change my code as follows:
    const handleOnClick = (e) => {
        e.preventDefault();
        console.log("You have clicked in the specified area")
    }

        return (
        <div>
            <img src={url} height={height} width={width} alt={alt} useMap="#workmap"/>
            <map id = "workmap" name="workmap">
                <area shape="poly" coords="50,47,56,454,257,357,254,139" alt="test" href="https://c1.staticflickr.com/5/4052/4503898393_303cfbc9fd_b.jpg" onClick={handleOnClick}/>
            </map>
        </div>
    )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM