On my website, data is displayed in a horizontal list. Each individual list item has a title and a button.
I’ve displayed it here https://codesandbox.io/p/sandbox/suspicious-platform-vj5td9
My task is that when you click on a div (id="main") with the value "first element", the color of the border changes from green to red. When you click on a div (id="main") with a value of "second element", the red color of the border with the "first element" is removed (and becomes green as before) and the border becomes red instead of the green of the "second element". However, when clicking on the "submenu" button, the border should not turn red.
const data = [
{ id: "1", title: "first element" },
{ id: "2", title: "second element" },
{ id: "3", title: "third element" },
];
export default function App() {
return (
<div>
{data.map((item) => (
<div id="main" className="App">
<div id="text">{item.title}</div>
<button>submenu</button>
</div>
))}
</div>
);
}
If you don’t understand something from my explanations, don’t hesitate to write to me.
2
Answers
If you want to change the border of a
div
depending on where the user clicks, you can achieve this using JavaScript. Here’s a simple example using HTML, CSS, and JavaScript:In this example, the
changeBorder
function is called when thediv
is clicked. The function checks the horizontal position of the click (event.clientX
) relative to the width of thediv
to determine if the left or right side was clicked. It then changes the border color accordingly.You can customize this example based on your specific requirements and styling preferences.
There were a few problems with your posted JSX, which we’ll discuss before looking at my proposed solution to the problem.
So, the original code with explanatory, and critical, comments in the code:
My proposed solution, then, is as follows:
Also, I updated the stylesheet to the following; purely for aesthetics – please adjust for your own needs – in order to make the borders a little more prominent and spread the elements out a little:
codesandbox.io demo.