Skip to content

Instantly share code, notes, and snippets.

@rockchalkwushock
Created January 10, 2018 14:26
Show Gist options
  • Save rockchalkwushock/09095ac6d42ed42128365113cf04bb4f to your computer and use it in GitHub Desktop.
Save rockchalkwushock/09095ac6d42ed42128365113cf04bb4f to your computer and use it in GitHub Desktop.
// The below is an example of writing a 'functional' component in React.
// The notes I made for the Component API are very high-level and quick so read the docs
// Since React@16 the docs have improved significantly!!!
// https://reactjs.org/docs/components-and-props.html#functional-and-class-components
// To better understand the component life-cycles use the following egghead.io tut
// https://egghead.io/courses/start-learning-react (I believe it is free!)
import React from 'react';
import { render } from 'react-dom'
const App = () => (
<div className="application">
<h1>Hello Wolrd</h1>
</div>
)
render.apply(<App />, document.getElementById('root'))
// Component API
import React, { Component } from 'react';
class App extends Component {
static defaultProps {
// default props
// Say the color of a button should start as 'blue'
}
static propTypes {
// you can use propTypes or flow for typechecking
// yarn add prop-types
// yarn add flow
}
state = {
// State on the component.
// If you are using `stage-2` for babel
// no need to declare constructor().
}
componentWillMount() {
// Before DOM is accessible.
// You don't have `window` or `document` here.
// This is more for server-side
}
componentDidMount() {
// Component in DOM.
// Make requests here
// i.e. fetch('/some-api') || axios.get('/chucknorris')
}
componentWillReceiveProps(nextProps) {
// Are we receiving props that will update the state
// of the component.
// i.e. User logs out and we need to update the view of
// this component.
}
shouldComponentUpdate(nextProps, nextState) {
// Really shouldn't touch this and let React do it's thing
// but if you need to Optimize look at the docs
// https://reactjs.org/docs/optimizing-performance.html#shouldcomponentupdate-in-action
}
componentWillUpdate(nextProps, nextState) {
// Similar to cwrp() above
}
componentDidUpdate(prevProps, prevState) {
// any final clean up to logic?
}
componentWillUnmount() {
// remove from DOM.
}
componentDidCatch(error, info) {
// Not as familiar with this new API
// but from what I understand errors from
// children components will bubble up and be
// caught here.
}
render() {
return <h1>Hello React!</h1>
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment