Skip to content

Instantly share code, notes, and snippets.

@mikeLspohn
Created April 23, 2018 03:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mikeLspohn/0ab8693c71b7fc52a6a31485e491e624 to your computer and use it in GitHub Desktop.
Save mikeLspohn/0ab8693c71b7fc52a6a31485e491e624 to your computer and use it in GitHub Desktop.
React 16.3.2 New Examples
// context
const UserContext = React.createContext({}) // {} is default value
// imagine this being a deeper child
const Page = props => <ContextProvider.Consumer>
{(user) => <p>{user.name}</p>}
</ContextProvider.Consumer>
class App extends Component {
state = {
user: {
id: 1,
name: 'guy'
}
}
render () {
return <UserContext.Provider value={this.state.user}>
<Page />
</UserContext.Provider>
}
}
// Refs
class AutoFocusInput extends Component {
constructor (props) {
super(props)
this.input = React.createRef()
}
componentDidMount () {
this.input.current.focus()
}
render () {
return <input
ref={this.input}
value={this.props.value}
onChange={this.props.onChange)
/>
}
}
// getDerivedStateFromProps (replace componentWillReceiveProps!)
class SomeComp extends Component {
constructor (props) {
super(props)
this.state = {}
}
// ** Arbitrary example. Wouldn't recommend using this just for this in real app **
//
// set state from next props if state/props are different
// else no update needed.
//
// This is ran during constructor initiatlization
// and when componentWilReceiveProps would have been ran
//
// Notice this is a static property, so there is no access to `this` instances
// of the class.
// The return value must be your next state, or null for no state update.
static getDerivedStateFromProps (nextProps, prevState) {
return (prevState.value !== nextProps.value)
? { value: nextProps.value }
: null
}
render () {
return (
<input value={this.state.value} />
)
}
}
// getSnapshotBeforeUpdate
class ScrollThing extends Component {
constructor (props) {
super(props)
this.listRef = React.createRef()
}
// replaces componentWillUpdate functionality
getSnapshotBeforeUpdate (prevProps, prevState) {
// capture scroll position if adding item
// return value gets called as 3rd arg in componentDidUpdate
if (prevProps.list.length < this.props.list.length) {
const list = this.listRef.current
return list.scrollHeight - list.scrollTop
}
}
componentDidUpdate (prevProps, prevState, snapshot) {
// set scroll height
if (snapshot !== null) {
const list = this.listRef.current
list.scrollTop = list.scrollHeight - snapshot
}
}
render () {
return <div ref={this.listRef}>{this.props.children}</div>
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment