Skip to content

Instantly share code, notes, and snippets.

@developit developit/_readme.md
Last active Feb 3, 2017

Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

commented Jun 27, 2016

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

@Venryx

This comment has been minimized.

Copy link

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
You can’t perform that action at this time.