Skip to content

Instantly share code, notes, and snippets.

@wochap
Last active October 15, 2016 19:41
Show Gist options
  • Save wochap/a04dcfcdc79362adae26 to your computer and use it in GitHub Desktop.
Save wochap/a04dcfcdc79362adae26 to your computer and use it in GitHub Desktop.
React examples

Basic component ES6

import React, { Component } from 'react'

export default class Todo extends Component {
  static propTypes = {
    text: React.PropTypes.string.isRequired
  }

  constructor (props) {
    super(props)
    this.state = { name: props.initialName || '' };
    this._handleClick = this._handleClick.bind(this)
  }

  _handleClick (event) {
    console.log(this)
    this.setState({name: this.state.name + 1});
  }

  render () {
    return (
      <li onClick={this._handleClick}>{ this.props.text + ' ' + this.state.name }</li>
    )
  }
}

Todo.propTypes = { text: React.PropTypes.string.isRequired }
Todo.defaultProps = { text: '' }

ReactDOM.render(
  <Todo text={'textito'} />,    
  document.getElementById('container')
);

Basic component BABEL stage-0

import React, { Component } from 'react'

export default class Todo extends Component {
  static propTypes = {
    text: React.PropTypes.string.isRequired
  }
  
  static defaultProps {
    text: ''
  }
  
  state = {
    name: this.props.initialName || ''
  }

  handleClick = (event) => {
    console.log(this)
    this.setState({name: this.state.name + 1});
  }

  render () {
    return (
      <li onClick={this.handleClick}>{ this.props.text + ' ' + this.state.name }</li>
    )
  }
}

ReactDOM.render(
  <Todo text={'textito'} />,    
  document.getElementById('container')
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment