Issue
My code has a component that displays the names of devices (available in the database). Here's an example
https://codesandbox.io/p/sandbox/dreamy-firefly-7xqypj
As you can see from the example above, when you click on any of the devices (within divs), the border color changes from green to red. Everything seems simple here and everything works well.
But I need to make sure that the color of the border does not change (remains green) when the "submenu" button is pressed (In the original code, when this button is clicked, a modal window opens). That is, if the user clicks anywhere on the div (except for the "submenu" button) -> the border color changes from green to red; but clicking on the "submenu" button should not affect the border color change
const data = [
{ id: "1", title: "Samsung" },
{ id: "2", title: "Iphone" },
{ id: "3", title: "LG" },
];
export default function App() {
const [active, setActive] = useState(null);
return (
<span id="main">
{data.map((item) => (
<div
onClick={() => setActive(item.id)}
className={item.id === active ? "active" : "App"}
>
<p>{item.title}</p>
<button>submenu</button>
</div>
))}
</span>
);
}
Solution
You'd need to add a stopPropagation event to the button:
<button onClick={(e) => { e.stopPropagation() }} >submenu</button>
import { useState } from "react";
import "./styles.css";
const data = [
{ id: "1", title: "Samsung" },
{ id: "2", title: "Iphone" },
{ id: "3", title: "LG" },
];
export default function App() {
const [active, setActive] = useState(null);
return (
<span id="main">
{data.map((item) => (
<div
onClick={() => setActive(item.id)}
className={item.id === active ? "active" : "notActive"}
>
<p>{item.title}</p>
<button
onClick={(e) => {
e.stopPropagation();
}}
>
submenu
</button>
</div>
))}
</span>
);
}
Answered By - Joseph
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.