1

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;

1
  • What do you mean by any string expression? Commented Aug 21, 2022 at 6:40

1 Answer 1

1

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.