Skip to content

Commit e64caf8

Browse files
authored
feat: Forward refs with lazy() (#57)
1 parent 57ce361 commit e64caf8

File tree

2 files changed

+28
-1
lines changed

2 files changed

+28
-1
lines changed

src/lazy.js

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,15 @@
11
import { h, options } from 'preact';
22
import { useState, useRef } from 'preact/hooks';
33

4+
const oldDiff = options.__b;
5+
options.__b = (vnode) => {
6+
if (vnode.type && vnode.type._forwarded && vnode.ref) {
7+
vnode.props.ref = vnode.ref;
8+
vnode.ref = null;
9+
}
10+
if (oldDiff) oldDiff(vnode);
11+
};
12+
413
export default function lazy(load) {
514
let p, c;
615

@@ -21,6 +30,7 @@ export default function lazy(load) {
2130
return p;
2231
}
2332

33+
LazyComponent._forwarded = true;
2434
return LazyComponent;
2535
}
2636

test/lazy.test.js

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import * as sinon from 'sinon';
44
import sinonChai from 'sinon-chai';
55

66
import { LocationProvider, Router } from '../src/router.js';
7-
import lazy from '../src/lazy.js';
7+
import lazy, { ErrorBoundary } from '../src/lazy.js';
88

99
const expect = chai.expect;
1010
chai.use(sinonChai);
@@ -42,4 +42,21 @@ describe('lazy', () => {
4242
await B.preload();
4343
expect(loadB).to.have.been.calledOnce;
4444
});
45+
46+
it('should forward refs', async () => {
47+
const A = () => <h1>A</h1>;
48+
const LazyA = lazy(() => Promise.resolve(A));
49+
50+
const ref = {};
51+
52+
render(
53+
<ErrorBoundary>
54+
<LazyA ref={ref} />
55+
</ErrorBoundary>,
56+
scratch
57+
);
58+
await new Promise(r => setTimeout(r, 1))
59+
60+
expect(ref.current.constructor).to.equal(A);
61+
});
4562
});

0 commit comments

Comments
 (0)