While working on React today, I got stuck somewhere because my basic JavaScript knowledge is not good.
I want to change the value of the “name” property of any object in this array.
Codesandbox: https://codesandbox.io/s/dank-rain-udjcxe?file=/src/App.js
JavaScript
x
5
1
const data = [
2
{ id: 1, name: "jonas" },
3
{ id: 2, name: "mark" },
4
{ id: 3, name: "elon" },
5
];
My App.js file
JavaScript
1
26
26
1
const App = () => {
2
const [people, setPeople] = useState(data);
3
4
5
6
const changePerson = (id) => {
7
// if I click on the button, the "name" value of the current object will change to anything
8
9
};
10
11
return (
12
<main>
13
<section>
14
{people.map((person) => {
15
return (
16
<div className="card" key={person.id}>
17
{person.name}
18
<button onClick={() => changePerson(person.id)}>change</button>
19
</div>
20
);
21
})}
22
</section>
23
</main>
24
);
25
};
26
export default App;
Advertisement
Answer
Essentially you need to create an updated array and set it. Use the callback method setPeople
to update the array. Try like this:
JavaScript
1
34
34
1
const data = [
2
{ id: 1, name: "jonas" },
3
{ id: 2, name: "mark" },
4
{ id: 3, name: "elon" }
5
];
6
7
const App = () => {
8
const [people, setPeople] = React.useState(data);
9
10
const changePerson = (id) => {
11
setPeople((prevPeople) =>
12
prevPeople.map((person) =>
13
person.id === id ? { person, name: "changed" } : person
14
)
15
);
16
};
17
18
return (
19
<main>
20
<section>
21
{people.map((person) => {
22
return (
23
<div className="card" key={person.id}>
24
{person.name}
25
<button onClick={() => changePerson(person.id)}>change</button>
26
</div>
27
);
28
})}
29
</section>
30
</main>
31
);
32
};
33
34
ReactDOM.render(<App />, document.querySelector('.react'));
JavaScript
1
3
1
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
2
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
3
<div class='react'></div>