Answer a question

I want to fire stop propagation method on event object that is inside a Link component from React-Router-Dom. My problem is that when I click on the button that is inside the Link element it moves me anyway to another page. I see that the stopPropagation method is not working properly and the onClick event on the Link element is firing up. How to prevent this behavior?

I have prepared an example on codeSandbox but in this example, Link is not moving me to another page but only refreshing the page.

Example https://codesandbox.io/s/serene-surf-h65dz?file=/src/Home.js

My Code:

const handleClick = e => {
  e.stopPropagation();
  return console.log("Works?");
};

return (
  <Link to={`/edytuj/${item.ID}`} className="table__row">
    <Checkbox
      isSelected={isSelected}
      toggleSelection={() => handleSelection(item, isSelected)}
    ></Checkbox>
    <TableRowItem>{item.ID}</TableRowItem>
    <TableRowItem
      src={item.IMAGE}
      additionalClassName="table__image"
    ></TableRowItem>
    <TableRowItem>{item.NAME}</TableRowItem>
    <TableRowItem>{item.DESCRIPTION}</TableRowItem>
    <TableRowItem additionalClassName="table__cost">
      {item.COST} zł
    </TableRowItem>
    <TableRowItem additionalClassName="table__buttons">
      <Button className="btn btn__edit" icon="fas fa-pen btn__icon">
        Edytuj
      </Button>
      <Button
        onClick={e => handleClick(e)}
        className="btn btn__delete"
        icon="fas fa-times btn__icon"
      >
        Usuń
      </Button>
    </TableRowItem>
  </Link>
);

Button:

const Button = ({ className, icon, children, onClick }) => {
  return (
    <button onClick={onClick} className={className}>
      {children}
      {icon && <i className={icon}></i>}
    </button>
  );
};

Answers

Just use e.preventDefault();

const handleClick = (e) => {
    e.preventDefault();
    return console.log("It works");
  };

https://codesandbox.io/s/small-bird-65zgb?file=/src/Home.js

Logo

React社区为您提供最前沿的新闻资讯和知识内容

更多推荐