最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - How to use svg image as a button in React - Stack Overflow

programmeradmin2浏览0评论

I have an issue making a clickable svg image in React. My image has a non-ordinary shape, that's why it's difficult for me. I want to know if it's possible to make all image clickable. Maybe it's can be solved in Html/Css

I have an issue making a clickable svg image in React. My image has a non-ordinary shape, that's why it's difficult for me. I want to know if it's possible to make all image clickable. Maybe it's can be solved in Html/Css

Share Improve this question asked Mar 28 at 8:27 Roman SorokaRoman Soroka 71 bronze badge
Add a comment  | 

1 Answer 1

Reset to default 1

Wrap your entire <svg> element in an <a> tag (if you want a link) or a <button> (if you want to trigger a JavaScript function). To make the entire SVG clickable regardless of its shape, set pointer-events: all; on the element itself (or on a container element around it). This will ensure clicks register even in the transparent areas within the SVG's bounding box.

React Example (Link):

import React from 'react';

function ClickableSVG() {
  return (
    <a href="https://www.stackoverflow" style={{ display: 'block' }}> 
      <svg style={{ pointerEvents: 'all', width: '200px', height: '200px' }} 
viewBox="0 0 100 100">

        {/* Your SVG path here */}

        <path d="M50,10 L90,90 L10,90 Z" fill="blue" /> {/* Example shape */}
      </svg>
    </a>
  );
}

export default ClickableSVG;

React Example (Button):

import React from 'react';

function ClickableSVG() {
  const handleClick = () => {
    alert('SVG Clicked!');
  };

  return (
    <button onClick={handleClick} style={{ display: 'block', padding: 0, 
border: 'none', background: 'none' }}>
      <svg style={{ pointerEvents: 'all', width: '200px', height: '200px' }} 
viewBox="0 0 100 100">

        {/* Your SVG path data here */}

        <path d="M50,10 L90,90 L10,90 Z" fill="blue" /> {/* Example shape */}
      </svg>
    </button>
  );
}

export default ClickableSVG;
发布评论

评论列表(0)

  1. 暂无评论