简体   繁体   中英

How to make a button inside of the anchor tag clickable in React?

I know that some relevant questions exist but none of them really has an answer more than saying that it is not possible. What I would like to achieve is having a dropdown button inside of an anchor tag so that user can be redirected on click but also has a possibility to interact with the button itself since it is a multiple-choice dropdown. Right now, once the user clicks on the button, the anchor tag redirects the user without having any effect on the button.

Just to give you an idea of what the code looks like, here is the minimal reproduction:

  <a href="some_location">
          <span>Some text</span>

          <div>
            <button>My Dropdown button</button>
          </div>
        </a>


i think it's can help you

const myComp = () => {

handelBtn = (e) => {
    e.stopPropagation();
    // OR
    e.preventDefault();
}
return (
    <a href="some_location">
        <span>Some text</span>

        <div>
            <button onClick={handelBtn}>My Dropdown button</button>
        </div>
    </a>
)
}

I think this can help you.

It works with both <Link> Component and <a> tag. Here <a> tag will be wrapped around the div(card) and div will work as <a> tag when clicked. The button will be above the <a> tag and it is clickable.

const myComp = () => {

return (
    <div class="card">
      <a href="some_location"> </a>
      <span>Some text</span>

      <div>
        <button>My Dropdown button</button>
      </div>
    </div>
)
.card {
    position: relative;
 }
 .card > a {
   position: absolute;
   inset: 0;
 }
 .card  button {
   position: relative;
 }

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