ES6+ for React
  • Introduction
  • Introduction
    • Introduction
  • Statements and declarations
    • let
    • const
    • class
    • import
    • export
  • Standard built-in objects
    • Arrow functions
    • Template literals
    • Array.prototype.map()
    • Computed property names
  • Expressions and operators
    • Spread operator
    • Destructuring assignment
    • Logical Operators
Powered by GitBook
On this page
  • Defination
  • Syntax
  • Usage
  • References

Was this helpful?

  1. Standard built-in objects

Computed property names

Defination

Starting with ECMAScript 2015, the object initializer syntax also supports computed property names. That allows you to put an expression in brackets [], that will be computed as the property name. This is symmetrical to the bracket notation of the property accessor syntax, which you might have used to read and set properties already. Now you can use the same syntax in object literals, too

Syntax

// Computed property names (ES2015)
var i = 0;
var a = {
};

console.log(a.foo1); // 1
console.log(a.foo2); // 2
console.log(a.foo3); // 3

var param = 'size';
var config = {
};

console.log(config); // {size: 12, mobileSize: 4}

Usage

class Reservation extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isGoing: true,
      numberOfGuests: 2
    };

    this.handleInputChange = this.handleInputChange.bind(this);
  }

  handleInputChange(event) {
    const target = event.target;
    const value = target.type === 'checkbox' ? target.checked : target.value;
    const name = target.name;

    this.setState({
      [name]: value
    });
  }

  render() {
    return (
      <form>
        <label>
          Is going:
          <input
            name="isGoing"
            type="checkbox"
            checked={this.state.isGoing}
            onChange={this.handleInputChange} />
        </label>
        <br />
        <label>
          Number of guests:
          <input
            name="numberOfGuests"
            type="number"
            value={this.state.numberOfGuests}
            onChange={this.handleInputChange} />
        </label>
      </form>
    );
  }
}

References

PreviousArray.prototype.map()NextSpread operator

Last updated 4 years ago

Was this helpful?

MDN Computed property names