Skip to content

Instantly share code, notes, and snippets.

@ETNOL
Last active August 1, 2017 00:40
Show Gist options
  • Select an option

  • Save ETNOL/c641f547140db7597e8a45ed773b0455 to your computer and use it in GitHub Desktop.

Select an option

Save ETNOL/c641f547140db7597e8a45ed773b0455 to your computer and use it in GitHub Desktop.
Typescript + React + Mixins
/*
* I'd been working on getting this pattern just right for adding common behaviors to class-based React components.
* The last hiccup I had was getting the state and props to inherit correctly from a mixin into a superclass and this
* appears to finally work as expected.
*/
import * as React from 'react'
type Component<P, S, T = React.Component<P, S>> = new (...args: any[]) => T
export interface ITogglableState {
isToggled: boolean
}
export interface ITogglableProps {
}
export function Togglable <TBase extends Component<ITogglableProps, ITogglableState>>(Base: TBase) {
return class extends Base {
constructor(...args) {
super(...args)
this.setState({...this.state, isToggled: false})
}
toggle() {
this.setState({
...this.state as {},
isToggled: !this.state.isToggled
})
}
}
}
/* example usage */
interface IProps {
name: string
}
interface IState extends ITogglableState {
}
class myClass extends Togglable(React.Component)<IProps, IState> {
constructor() {
this.state = { isToggled: false }
}
render() {
return (
<div>
<div hidden={this.state.isToggled}>
{this.props.name}
<button onClick={this.toggle}>Hide</button>
</div>
<button hidden={!this.state.isToggled} onClick={this.toggle}>Show</button>
</div>
)
}
// The mixin's methods could also be overridden with support for calling super to them:
// toggle() {
// console.log('mixin toggle is being called')
// super.toggle()
// console.log('mixin toggle was called')
// }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment