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.
Try this example live on CodePen
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'))
componentDidMount() is invoked immediately after a component is mounted. Initialization that requires DOM nodes should go here.
import React, { Component } from 'react'
class MyComponent extends Component {
componentDidMount() {
this.nameInput.focus()
}
render() {
return (
<input
ref={(input) => { this.nameInput = input; }}
defaultValue="will focus"
/>
)
}
}
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!'
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,
}
}
Property initializers are a Stage 2 proposal for ECMAScript, meaning that it’s still a draft and is subject to minor changes before becoming standardized. Facebook itself is already using these techniques in production, however.
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 });
}
}
Finish all the bonus work from yesterday.
Sidebar clear out the form with a blank note. (Then you can get rid of the save and new button in NoteForm).