Skip to content

Instantly share code, notes, and snippets.

@developit
Last active February 3, 2017 15:01
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save developit/63e7a81a507c368f7fc0898076f64d8d to your computer and use it in GitHub Desktop.
Like linkState(), but for Refs.

Simple, unobtrusive add-on to support String refs in Preact, without needing to pull in preact-compat.

Option 1: Add-on

Calling linkRef(componentInstance, refName) returns a "ref proxy" function, which sets this.refs[refName] when called.

import { h, Component } from 'preact';
import linkRef from './linked-ref';

class Example extends Component {
    render() {
        return (
            <div>
                <Child ref={linkRef('one')} />
                <Child ref={linkRef('two')} />
            </div>
        );
    }
}

Option 2: Patched into Component

linked-ref.js also injects a .linkRef(name) method into Preact's Component class, to match how .linkState() works:

import { h, Component } from 'preact';
import './linked-ref';

class Example extends Component {
    render() {
        return (
            <div>
                <Child ref={this.linkRef('one')} />
                <Child ref={this.linkRef('two')} />
            </div>
        );
    }
}
import { Component } from 'preact';
// OPTIONAL: patch Component by default (you might want to delete this if you're a purist)
Component.prototype.linkRef = function(name) {
return linkRef(this, name);
};
// Export the linker as a standalone function:
export default function linkRef(component, name) {
let cache = component._linkedRefs || (component._linkedRefs = {});
if (!component.refs) component.refs = {};
return cache[name] || (cache[name] = c => {
component.refs[name] = c;
});
}
@developit
Copy link
Author

note: delete Component.prototype.linkRef if you don't want that bit, it's a little ugly.

@Venryx
Copy link

Venryx commented Feb 3, 2017

First example is missing the "this" argument in both of the linkRef calls.

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