Skip to content
Branch: master
Find file Copy path
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
executable file 68 lines (53 sloc) 2.01 KB
name permalink
Extending Component

Extending Component

It is possible that some projects would wish to extend Component with additional functionality.

There are varying opinions on the value of inheritance in JavaScript, but if you wish to build your own "base class" from which all of your components inherit, Preact has you covered.

Perhaps you want to do automatic connection to stores/reducers within a Flux-like architecture. Maybe you want to add property-based mixins to make it feel more like React.createClass() (note: the @bind decorator is preferable).

In any case, just use ES2015 class inheritance to extend Preact's Component class:

class BoundComponent extends Component {
    // example: get bound methods
    binds() {
        let list = this.bind || [],
            binds = this._binds;
        if (!binds) {
            binds = this._binds = {};
            for (let i=list.length; i--; ) {
                binds[list[i]] = this[list[i]].bind(this);
        return binds;

Example Usage:

class Link extends BoundComponent {
    bind = ['click'];
    click() {
    render({ children }) {
        let { click } = this.binds();
        return <span onClick={ click }>{ children }</span>;

    <Link href="">Click Me</Link>,

The possibilities are endless. Here's an extended Component class that supports rudimentary mixins:

class MixedComponent extends Component {
    constructor() {
        (this.mixins || []).forEach( m => Object.assign(this, m) );

Footnote: It's worth noting that inheritance can lock you into brittle parent-child relationships. Often when faced with a programming task that can be solved adequately with inheritance, there is a more functional way to achieve the same goal that would avoid creating such a relationship.

You can’t perform that action at this time.