skip to Main Content

I have a div that is inside an "a" tag (Link in next.js), and there is also a "like" div inside it. If I click anywhere in the div, I want it to take me where the "a" tag points. However, if I click on the "like" div, I don’t want it to take me anywhere; instead, I want a JavaScript script to be triggered.

How to do this? Is there any other way? How should it look to be both functional and SEO-friendly?

On Twitter, there’s something similar: the entire "tweet" is clickable and takes you to another page, whereas buttons like "like" work as they should, and that’s the effect I want to achieve.

'use client'
import React from 'react'

interface LikeTypes {
    likes:number
}

function LikeCard({likes}:LikeTypes ) {

    const likeButtonClicked= () => {

      };
    

  return (
    <div className='flex justify-center items-center ' onClick={(e) => { e.nativeEvent.stopImmediatePropagation(); likeButtonClicked(); }}>❤ {likes}</div>
  )
}

export default LikeCard

i tried use
e.nativeEvent.stopImmediatePropagation();
but is not working.

part of outside component wraping LikeCard

    <Link href={href}>
                  <LikeCard likes={likes}/>
    </Link>

2

Answers


  1. preventDefault should work

    document.querySelector('button').addEventListener('click', e => {
      e.preventDefault()
    })
    <a href="https://stackoverflow.com">
      Post: <button>Like</button>
    </a>
    Login or Signup to reply.
  2. You can use one of the two approaches here.

    1. with the event object passed to the event handler.

      function someFunction (event) {

      event.preventDefault();
      

      }

      this is stop the browsers default behavior.

    2. Secondly with href="javascript:void(0)"

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search