Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ignore an element inside <Link></Link> to not navigate on click

I'm trying to get to work a delete btn which is inside a div which is wrapped in react-router-dom tag. I want to be able to navigate to the established path when that div is clicked. But if the target is that delete btn, then it shouldn't navigate just execute the onClick inside the delete btn. Is this possible? I couldn't figure out on my own. Thanks for reading.

<ul className="m-entries">    
  {
    letters.map(letter => {        
      return (
        <li className="o-entry" key={ letter.id }>
          <Link to={`/Letters/letter/${ letter.id }`}>
            <div className="l-entry-container">
              <div className="l-entry__header">
                <h2 className="c-text__h2 c-letter-title">{ letter.title }</h2>
                // This is the delete btn
                <button 
                  className="c-entry__btn c-entry__dlt-btn"
                  onClick={(e) => {                        
                    displayConfirmDeleteWdw(e, letter.id)
                  }}
                  type="button"
                >                    
                  <XDeleteBtn />                      
                </button>                                
              </div>              
              <p className="c-text__p c-letter__preview">{ letter.synopsis }</p>
            </div>                
          </Link>
        </li>           
    )})
  }                  
</ul>
like image 429
glowbo Avatar asked Oct 18 '25 10:10

glowbo


1 Answers

It's generally considered bad UI/UX to place interactive DOM elements within other interactive DOM elements (in fact some elements are sometimes illegal when used like this), but there is a way to accomplish this.

The button's onClick event should not propagate up to the Link component. Call stopPropagation on the event to prevent it from bubbling up further.

<ul className="m-entries">
  {letters.map(letter => {
    return (
      <li className="o-entry" key={letter.id}>
        <Link to={`/Letters/letter/${letter.id}`}>
          <div className="l-entry-container">
            <div className="l-entry__header">
              <h2 className="c-text__h2 c-letter-title">{letter.title}</h2>
              <button
                className="c-entry__btn c-entry__dlt-btn"
                onClick={(e) => {
                  e.stopPropagation(); // <-- prevent event from bubbling up
                  displayConfirmDeleteWdw(e, letter.id);
                }}
                type="button"
              >
                <XDeleteBtn />      
              </button>
            </div>
            <p className="c-text__p c-letter__preview">{letter.synopsis}</p>
          </div>
        </Link>
      </li>
    )})
  }
</ul>
like image 195
Drew Reese Avatar answered Oct 22 '25 05:10

Drew Reese