Notes on React, pt 1: Novel ES6 Syntaxes

This post will be the first in an ongoing series as I learn React, and share knowledge with other devs at Kiddom.

ES6

ES6 or Ecma script 2016 is a variant of Javascript. This post lays out some of the syntaxes I’ve discovered and found very useful or fun.

New browsers support it natively. Others require a transpiler, like Babel. (Means you need to include the Babel js file in your HTML above any es6 script tags.)

Support for ECMAScript is messy, because there seems to be several new versions (called specs) evolving via debates and additions over time. I’m going to generally refer to “Stage-0″ which is essentially the nightly / dev build of the syntax. We risk some standards changing and requiring that we update our source, but get all the newest cool stuff.

Spreaders

Spreaders mean “and the rest of”. They support arrays and objects, with basically the same idea.

Array Spreader

[js]
array = [1,2]
newArray = [ …array, 3]
// newArray: [1, 2, 3]
[/js]

The spread operator (“…”) spreads the contents of array out into the definition of the new array, where a new value is appended.

Object Spreader

[js]
obj = {
foo: true,
bar: false,
}
newObj = {
…obj,
bar: true,
baz: true,
}
// newObj: { foo: true, bar: true, baz: true }
[/js]

Order matters with both kinds of spreaders! (Note that bar = true in newObj, overwritten by the rest of the definition)

JSX Spreader

[js]

[/js]

Use what looks like an object spreader to pass an object full of properties to the recipient component.

Deconstruction

A really neat shorthand for pulling specific values out of an object.

Basic Example

[js]
{ foo } = { foo: true }
// foo === true
[/js]

Deconstructing Arguments to a Function

[js]
const fooBar = ({ foo }) => console.log(foo)
fooBar({ foo: true, bar: “ignored”})
// logs `true`
[/js]

Destructuring while Renaming

[js]
{ oldName: newName } = { oldName: true }
// newName === true
[/js]

Yes, this looks a little backwards, given that it functions like `newName = {…}.oldName`. I say in my head “Pull out oldName, as newName” so it makes more sense left-to-right.

Jordan is a freelance engineer with full-stack chops, and an eye for analytics and growth.

Trackbacks

  1. […] This is post #2 in an ongoing series as I learn React, and share knowledge with other devs at Kiddom. Start at the first. […]

  2. […] This is post #3 in an ongoing series as I learn React, and share knowledge with other devs at Kiddom. Start at the first. […]