How to add a class name in every row without effect the rest of the rows
JavaScript
x
45
45
1
import React, { useState } from 'react';
2
import './testEfect.css';
3
4
const Test = () => {
5
6
const arrayTest = [
7
{
8
name: '11',
9
id: '11'
10
},
11
{
12
name: '22',
13
id: '22'
14
},
15
{
16
name: '33',
17
id: '33'
18
},
19
]
20
21
const [state, setState] = useState(false);
22
23
const handleClick = (event) => {
24
const newState = event;
25
26
setState(state ? false : true);
27
28
}
29
30
return (
31
<div className="App">
32
{arrayTest.map((x, index) => {
33
return (
34
<ul key={index} className={state ? 'deletEfect' : ''}>
35
<li id={x.id} >
36
{x.name}
37
<button onClick={(event) => handleClick(x.id)}>Delete</button>
38
</li>
39
</ul>
40
)
41
})}
42
</div>
43
)
44
}
45
Advertisement
Answer
The problem here is that when you say the state is false; it is assuming the state is false for the whole component. It doesn’t update the row but the whole component. So, at first, you need to add a deleted property that will take a different value for each row.
So,
JavaScript
1
20
20
1
const arrayTest = [
2
{
3
name: "11",
4
id: "11",
5
deleted: false
6
},
7
{
8
name: "22",
9
id: "22",
10
deleted: false
11
},
12
{
13
name: "33",
14
id: "33",
15
deleted: false
16
}
17
];
18
19
const [state, setState] = useState(arrayTest); //initial state
20
Now, when you render, you don’t need to use that arrayTest. But you need to use the state. We won’t touch arrayTest ever again. So we use,
JavaScript
1
11
11
1
{state.map((x, index) => {
2
return (
3
<ul key={index} className={x.deleted ? "testEfect" : ""}>
4
<li id={x.id}>
5
{x.name}
6
<button onClick={(event) => handleClick(x.id)}>Delete</button>
7
</li>
8
</ul>
9
);
10
})}
11
Notice we use state.map
. We also send x.id
to handleClick
function.
Why? Because we will use that id to change the deleted value of the object. So our handleClick
becomes,
JavaScript
1
11
11
1
const handleClick = (id) => {
2
const newState = state.map((element) => {
3
if (element.id === id)
4
return Object.assign({}, element, {
5
deleted: element.deleted ? false : true
6
});
7
return element;
8
});
9
setState(newState);
10
};
11
This is just updating the state in an immutable way.
Here is the full codesandbox for your convenience.