Simple, unobtrusive add-on to support String refs in Preact, without needing to pull in preact-compat.
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>
);
}
}
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>
);
}
}
note: delete
Component.prototype.linkRef
if you don't want that bit, it's a little ugly.