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
const data = [
{ id: 1, name: "jonas" },
{ id: 2, name: "mark" },
{ id: 3, name: "elon" },
];
My App.js file
const App = () => {
const [people, setPeople] = useState(data);
const changePerson = (id) => {
// if I click on the button, the "name" value of the current object will change to anything
};
return (
<main>
<section>
{people.map((person) => {
return (
<div className="card" key={person.id}>
{person.name}
<button onClick={() => changePerson(person.id)}>change</button>
</div>
);
})}
</section>
</main>
);
};
export default App;
CodePudding user response:
Essentially you need to create an updated array and set it. Use the callback method setPeople
to update the array. Try like this:
const data = [
{ id: 1, name: "jonas" },
{ id: 2, name: "mark" },
{ id: 3, name: "elon" }
];
const App = () => {
const [people, setPeople] = React.useState(data);
const changePerson = (id) => {
setPeople((prevPeople) =>
prevPeople.map((person) =>
person.id === id ? { ...person, name: "changed" } : person
)
);
};
return (
<main>
<section>
{people.map((person) => {
return (
<div className="card" key={person.id}>
{person.name}
<button onClick={() => changePerson(person.id)}>change</button>
</div>
);
})}
</section>
</main>
);
};
ReactDOM.render(<App />, document.querySelector('.react'));
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div class='react'></div>