How to remove a key from state object in React.js

There are situations where we want to remove a key from an object inside a component’s state. If this is required, we must be careful not to mutate our original state.

With this in mind, how can you remove a key from a state object in React.js?

A key can be removed safely from a component’s state by utilizing Object.assign(). This allows us to clone the component’s state without mutating the original object.

This is demonstrated in the following example (JSfiddle).

Let’s say we have the Characters component:

class Characters extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: {
        name: "Tommy Vercetti",
        location: "Vice City",
      },
    };
  }

 render() {
    const { data } = this.state;
    return (
      <div>
        <h2>Characters:</h2>
        <ol>
          <li>{data.name}</li>
          <li>{data.location}</li>
        </ol>
      </div>
    );
  }
}

This gives us the following UI:

In its state, there is a list of characters with name and location properties:

data: {
  { name: "Tommy Vercetti", location: "Vice City" },
};

Let create a removeKeymethod that will delete an object by its key:

removeKey = (keyname) => {
    const updatedState = {
      data: {
        name: "Tommy Vercetti",
      },
    };
    this.setState(updatedState);
  };

And finally, let’s call removeKey function onClick:

<h2 onClick={() => this.removeKey()}>Characters:</h2>

Let’s break this down:

  • Create a new state in a separate variable updatedState 
  • Add new object with the locationproperty removed.
  • We then update the state using this.setState() with our updatedState value.

This click results in location being removed in the UI:

And there you have it. We have effectively removed a property key in React.

Gareth Dunne

Senior JavaScript Engineer and creator of JSdiaries. Passionate about the latest in web technologies and how it can provide value for my clients.