Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
8
rated 0 times [  12] [ 4]  / answers: 1 / hits: 7756  / 4 Years ago, thu, july 2, 2020, 12:00:00

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>
);
};

More From » reactjs

 Answers
2

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


[#3308] Monday, June 29, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
monetm

Total Points: 615
Total Questions: 103
Total Answers: 119

Location: Finland
Member since Fri, Oct 21, 2022
2 Years ago
monetm questions
Fri, Feb 26, 21, 00:00, 3 Years ago
Wed, Sep 9, 20, 00:00, 4 Years ago
Sun, Jul 26, 20, 00:00, 4 Years ago
Thu, Jun 11, 20, 00:00, 4 Years ago
;