Skip to content

Instantly share code, notes, and snippets.

@developit
Last active July 25, 2023 12:54
Show Gist options
  • Save developit/974b5e4e582df8e954c5a7981603cd37 to your computer and use it in GitHub Desktop.
Save developit/974b5e4e582df8e954c5a7981603cd37 to your computer and use it in GitHub Desktop.

Standalone forwardRef

import { forwardRef } from 'preact-forwardref';

const Foo = forwardRef((props, ref) => {
  return <div ref={ref} />
});

render(<Foo ref={div => console.log(div)} />, document.body);
{
"name": "preact-forwardref",
"version": "0.1.0",
"description": "standalone preact forwardRef",
"repo": "gist:974b5e4e582",
"homepage": "https://gist.github.com/974b5e4e582df8e954c5a7981603cd37",
"type": "module",
"main": "preact-forwardref.js",
"types": "./types.d.ts",
"scripts": {
"prepack": "mv '*Preact forwardRef.md' README.md",
"postpack": "mv README.md '*Preact forwardRef.md'"
}
}
import{options}from'preact';
options.__b = function(o,v) {
if (v.type && v.type._f && (v.props.ref=v.ref)) v.ref = null;
o && o(v);
}.bind(0,options.__b);
export function forwardRef(fn) {
function F(p) {var ref=p.ref;delete p.ref;return fn(p, ref)}
return F._f = F;
}
import { Ref, FunctionComponent, ComponentChild } from "preact";
export function forwardRef<RefType, Props>(
component: (props: Props, ref: Ref<RefType>) => ComponentChild
): FunctionComponent<Props & { ref?: Ref<RefType> }>;
@rubencodes
Copy link

In case it's helpful to anyone, I wrote up some (maybe correct? it seems to work right) types:

declare module "preact-forwardref" {
	import { Ref, FunctionComponent, ComponentChild } from "preact";

	export function forwardRef<RefType, Props>(
		render: (props: Props, ref: Ref<RefType>) => ComponentChild
	): FunctionComponent<Props & { ref?: Ref<RefType> }>;
}

@developit
Copy link
Author

Thanks @rubencodes!! I've just added your types to the package and published 0.2.0.

@rubencodes
Copy link

Amazing, thank you! 🙇

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