Skip to content

Instantly share code, notes, and snippets.

@neogeek
Last active October 27, 2016 19:30
Show Gist options
  • Save neogeek/5e25f80508d29470436c038fed1eebdb to your computer and use it in GitHub Desktop.
Save neogeek/5e25f80508d29470436c038fed1eebdb to your computer and use it in GitHub Desktop.
Advanced React Notes

Advanced React Notes

Destruct Object

const { isActive, label, description } = this.props;

Ref Callback

toggleVisibility () {

  const { isOpen } = this.props

  if (isOpen) {
    $(this.modal).modal('show')
  } else {
    $(this.modal).modal('hide')
  }

}
<div ref={(node) => this.modal = node} />

onClick Handler

<div onClick={isDisabled ? null : () => this.handleClick()} />

Passing Properties to Children

const children = React.Children.map(this.props.children, (child) => {
  console.log(child.type); // Returns reference to component object
  const isActive = this.props.activeIndex === index;
  return React.cloneElement(child, {
    isActive
  });
})

Context

DO NOT USE, or do? ¯\_(ツ)_/¯

class Form extends React.Component {
  static propTypes = {
    onSubmit: React.PropTypes.func.isRequired,
    children: React.PropTypes.node
  }
  static childContextTypes = {
    form: React.PropTypes.shape({
      onSubmit: React.PropTypes.func.isRequired
    })
  }
  getChildContext() {
    return {
      form: {
        onSubmit: this.props.onSubmit
      }
    }
  }
  render() {
    return <div>{this.props.children}</div>
  }
}
class SubmitButton extends React.Component {
 static propTypes = {
   children: React.PropTypes.node
 }
 static contextTypes = {
   form: React.PropTypes.shape({
     onSubmit: React.PropTypes.func.isRequired
   })
 }
 render() {
   return <button onClick={this.context.form.onSubmit}>{this.props.children}</button>
 }
}

Render Callbacks

class Module extends React.Component {
  state = {
    items: [ 'test', 'test2' ]
  }

  render() {
    return this.props.children(this.state)
  }
}
class App extends React.Component {
  render() {
    return (
      <Module>
      {state => <div>{state.items.map((item, index) => (<p key={index}>{item}</p>))}</div>}
      </Module>
    )
  }
}

defaultValue

<input name="name" defaultValue={this.state.name} />

window.matchmedia

https://developer.mozilla.org/en-US/docs/Web/API/Window/matchMedia

O_o

Class Inheritance is ☹️ Upon

Use higher-order components instead.

shouldComponentUpdate

class Item extends React.Component {

  shouldComponentUpdate(nextProps) {
    return nextProps.description !== this.props.description
  }

  render () {
    <p>{this.props.description}</p>
  }

}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment