Can we access state properties using bracket notation?

Question

In the context of this exercise, can we access state properties using bracket notation?

Answer

Yes, component state is essentially a JavaScript object, so you can access the properties using dot notation as well as bracket notation.

For example,

this.state['key'];

Using bracket notation allows us to select property names that have special characters or spaces that we otherwise could not select using dot notation. For instance,

this.state = {
  "key 1": value
}

/* Not valid */
this.state.key 1;

/* Valid */
this.state["key 1"];
10 Likes