Why I can’t toggle the className in each div?
I want to give each div a green border when I double click on h1 tag inside each div
and
when I double click again I want border to disapper
I put image for you to understand my situation
If you don’t get the problem comment under the question
JavaScript
x
56
56
1
const { useState, Fragment } = React;
2
const tasks = [
3
{
4
id: 1,
5
title:
6
"sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
7
body: "quia et suscipitnsuscipit recusandae consequuntur expedita et cumnreprehenderit molestiae ut ut quas totamnnostrum rerum est autem sunt rem eveniet architecto",
8
reminder: false,
9
},
10
{
11
id: 2,
12
title: "qui est esse",
13
body: "est rerum tempore vitaensequi sint nihil reprehenderit dolor beatae ea dolores nequenfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendisnqui aperiam non debitis possimus qui neque nisi nulla",
14
reminder: false,
15
},
16
{
17
id: 3,
18
title: "ea molestias quasi exercitationem repellat qui ipsa sit aut",
19
body: "et iusto sed quo iurenvoluptatem occaecati omnis eligendi aut adnvoluptatem doloribus vel accusantium quis pariaturnmolestiae porro eius odio et labore et velit aut",
20
reminder: false,
21
},
22
];
23
24
function Tasks() {
25
const [initial_tasks, setTasks] = useState(tasks);
26
const onDelete = (the_id) => {
27
setTasks(initial_tasks.filter((task) => task.id !== the_id));
28
};
29
const toggle = function (the_id) {
30
setTasks(
31
tasks.map((task) =>
32
task.id == the_id ? { task, reminder: !task.reminder } : task
33
)
34
);
35
};
36
37
return (
38
<Fragment>
39
{initial_tasks.length
40
? initial_tasks.map((task) => (
41
<div className={`task ${task.reminder ? "reminder-style" : ""}`}>
42
<h1 onDoubleClick={() => toggle(task.id)}>{task.id}</h1>
43
<p
44
onClick={() => {
45
onDelete(task.id);
46
}}
47
>
48
{task.title}
49
</p>
50
</div>
51
))
52
: "no items"}
53
</Fragment>
54
);
55
}
56
JavaScript
1
4
1
.reminder-style {
2
border: 3px solid green;
3
}
4
JavaScript
1
4
1
<div id="root"></div>
2
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.0.0/umd/react.development.js"></script>
3
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.0.0/umd/react-dom.development.js"></script>
4
Advertisement
Answer
Check this part of the code.
JavaScript
1
9
1
const toggle = function (the_id) {
2
setTasks(
3
tasks.map((task) =>
4
task.id == the_id ? { task, reminder: !task.reminder } : task
5
)
6
);
7
};
8
9
You are always checking with tasks
variable which is a constant value. Instead of that use your initial_tasks
. You’ll get your functionality.