Morning:
Afternoon:
Sometimes one component needs to update another component’s state. It can’t do that directly, but it can call a method from that other component if it’s available via a prop.
import React from 'react'
import ReactDOM from 'react-dom'
const PartyButton = ({ celebrate, celebrations }) => {
return <button onClick={celebrate}>Party! {celebrations}</button>
}
class App extends React.Component {
constructor() {
super()
this.state = {
celebrations: 0,
}
this.celebrate = this.celebrate.bind(this)
}
celebrate() {
const celebrations = this.state.celebrations + 1
this.setState({ celebrations })
}
render() {
return <PartyButton celebrate={this.celebrate} celebrations={this.state.celebrations} />
}
}
ReactDOM.render(<App />, document.querySelector('main'))
Destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.
const myObj = {
a: true,
b: 'Destructuring!'
}
let { a, b } = myObj
console.log(a) // => true
console.log(b) // => 'Destructuring!'
Property initializers are a Stage 3 proposal for ECMAScript, meaning that they’re a candidate, but requires further refinement and feedback from implementations and users before it becomes part of the standard. Facebook itself is already using these techniques in production, however.
From the proposal:
“Class instance fields” describe properties intended to exist on instances of a class (and may optionally include initializer expressions for said properties).
We can take advantage of this in React.
Read more: Using ES7 property initializers in React
We can use a property initializer to set the initial value of state without writing a constructor:
class Song extends React.Component {
state = {
versesRemaining: 5,
}
}
We can even set default props and use those in the initial state:
class Song extends React.Component {
static defaultProps = {
autoPlay: false,
verseCount: 10,
}
state = {
versesRemaining: this.props.verseCount,
}
}
Combining property initializers and arrow functions gives us a convenient way to auto-bind this, since arrow functions inherit this from the scope in which they are declared (lexical scoping):
class Something extends React.Component {
handleButtonClick = (ev) => {
// `this` is bound correctly!
this.setState({ buttonWasClicked: true });
}
}
localStorage.