Search code examples
javascriptreactjsreact-routerreact-bootstrap

React-Router Link


I am using react-bootstrap components (Card). I want to get redirected to '/abc:id' when clicked on the attachment link. But getting redirected to '/xyz' while wanting it to redirect '/xyz' when clicked on the anywhere on card but Attachment.

 <Card
   className={classes.style1}
     onClick={() => history.push({
     pathname: '/xyz'
   })}
 >
   <Card.Body>
      <Link to={'/abc'+id} className="text-info">
         <i className="fas fa-paperclip" />
          <span> Attachment</span>
      </Link>
    </Card.Body>
</Card>

Solution

  • You can stopPropagation, as currently it is going to /xyz after /abc:id.

    <Link
      to={'/abc'+id}
      className="text-info"
      onClick={e => e.stopPropagation()}
    >
    

    stopPropagation stops the event from bubbling up the event chain. You can check this answer.


    Or you can wrap your Card in a Link and remove onClick from Card.

    <Link
      to={{
        pathname: '/xyz',
      }}
    >
      <Card className={classes.style1}>
        <Card.Body>
          <Link to={`/abc${id}`} className="text-info">
            <i className="fas fa-paperclip" />
            <span> Attachment</span>
          </Link>
        </Card.Body>
      </Card>
    </Link>