Skip to content

Instantly share code, notes, and snippets.

@kilgarenone
Last active June 21, 2018 07:28
Show Gist options
  • Save kilgarenone/9ea4272eacd818c450d03e9a453f3e18 to your computer and use it in GitHub Desktop.
Save kilgarenone/9ea4272eacd818c450d03e9a453f3e18 to your computer and use it in GitHub Desktop.
Rundown of a React Component Class in Typescript
import * as React from 'react'
import { connect } from 'react-redux'

// props that you pass in from the parent component
interface ExposedProps {
  someExposedProp?: any,
}
/*
 The 'someStateSelector' method could be a 'reselect' type of selector.
 https://github.com/reactjs/reselect#reselect. This is good for computational heavy stuff.
 
 Or, it could just be a function that accepts 'state' and return a key in the state tree.
 `(state) => state.myValue.realValue`
 
 Or, you can directly write `state.myValue.realValue` here, which is not advisable :)
*/
const mapStateToProps = (state: State) => {
  return {someState: someStateSelector(state)}
}

// short-hand dispatch syntax ftw
// Source: https://goo.gl/jUSGu6
const mapDispatchToProps = { 
  someDispatcher: () => {},
}
const mapStateToPropsTypeMaker = returnType(mapStateToProps)
type ReduxStates = typeof mapStateToPropsTypeMaker

// 'Props' is the total of all these props on the right side assignment
type Props = ExposedProps & typeof mapDispatchToProps & ReduxStates

class $name$Base extends React.Component<Props> {
  // Define 'state' like this. 
  // If need to assign props to state or access props in constructor, 
  // then use the 'constructor' pattern.
  // Source: https://stackoverflow.com/a/34995257/73323
  state = {}

  /* This arrow function pattern for class's method is a good alternative 
    to write this common pattern seen in the react's doc.
    
    constructor(props) {
      super(props);
      this.state = {isToggleOn: true};

      // This binding is necessary to make `this` work in the callback
      this.handleClick = this.handleClick.bind(this);
    }

    The arrow function automatically bind the 'this' context for you!
    Source: https://goo.gl/oxneP3

  */
  classMethod = () => {}
  
  render() {
      return null;
  }
}

export const $name = connect(
  mapStateToProps,
  mapDispatchToProps
)($name$Base as any) as any as React.ComponentClass<ExposedProps>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment