Changing the state of a JSON object in React

Changing the state of a JSON object in React

·

2 min read

Table of contents

No heading

No headings in the article.

In this code example, we see how to change the state of a JSON object in a React component. This is a common task when building interactive user interfaces because it allows us to update the data that we display in response to user actions.

import React, { useState } from 'react';

function Example() {
  // Declare a new state variable, which we'll call "json"
  const [json, setJson] = useState({
    name: 'John Doe',
    age: 42,
    address: {
      street: '123 Main St.',
      city: 'Boston',
      state: 'MA'
    }
  });

  // This function updates the "json" state by changing the "name" property
  const updateName = () => {
    setJson({
      ...json, // copy the current properties of "json"
      name: 'Jane Doe' // update the "name" property
    });
  };

  return (
    <div>
      <p>Name: {json.name}</p>
      <button onClick={updateName}>Update Name</button>
    </div>
  );
}

In this example, the Example component has a state variable called json that is initialized with a JSON object containing some data. The component renders the name property of the json object, and has a button that, when clicked, updates the name property of the json object.

To update the json state, the code uses a common pattern in React: it creates a new json object by copying the current properties of the existing json object, and then updating the name property with a new value. This allows us to keep the existing state and only change the properties that we want to update.

Overall, this code shows how to use React's state mechanism to manage data in a JSON object and update it in response to user actions. This is a valuable skill for any front-end developer building interactive user interfaces with React.

Did you find this article valuable?

Support Olgun by becoming a sponsor. Any amount is appreciated!