简体   繁体   中英

How to create a button component inside of a react-router Link that does not redirect?

I am trying to create a component where I have a button inside an entire element that is a Link that takes you elsewhere.

see picture, where entire white block is a link and the button is the lock icon

I've seen various buttons about using e.stopPropagation() or e.preventdefault() but none seem to work. This is what I am doing right now:

<Link to={`/editAccount/${account._id}`} key={account._id} className="friend displayHorizontallyNoSpaceBetween curveAll transition lightGrayBG">
      <div style={{background: account.color}} className="firstLetter curveLeft centerSelf righteous lightGray">
          {account.account_name[0].toUpperCase()}
      </div>
      <div className="info">
          <h3 className="wordWrap">{account.account_name}</h3>
          <h6>Your account</h6>
      </div>
      <div className="darkGray centerSelf myAccountsFlexEndPrice">
          <IconButton onClick={(event) => {
              event.stopPropagation();
              this.togglePrivacy(event)
          }}> 
              <LockOpenOutlinedIcon style={{ fontSize: 16}} />
          </IconButton>
      </div>
      <div className="myAccountsFlexEndPrice paddingPriceMyAccounts centerSelf darkGray">
          <div className="priceText">
              ${account.total_price.toFixed(2)}
          </div>
                  
      </div>
</Link>

Essentially what I want is for the function inside the IconButton , which is togglePrivacy(event) to be called without the page navigating to the new link. Any recommendations?

Try event.preventDefault() . It looks like you need to capitalize the D .

<IconButton onClick={(event) => {
    event.preventDefault();
    this.togglePrivacy(event);
}}>
    {...code}
</IconButton>

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