Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Forward refs with lazy() #57

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions src/lazy.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,15 @@
import { h, options } from 'preact';
import { useState, useRef } from 'preact/hooks';

const oldDiff = options.__b;
options.__b = (vnode) => {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When compat is imported this would exist twice, not a bad thing necessarily just wanted to point it out

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Indeed, I'm not aware of any side effects though, are there any? If so, any good ways to avoid it?

if (vnode.type && vnode.type._forwarded && vnode.ref) {
vnode.props.ref = vnode.ref;
vnode.ref = null;
}
if (oldDiff) oldDiff(vnode);
};

export default function lazy(load) {
let p, c;

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

LazyComponent._forwarded = true;
return LazyComponent;
}

Expand Down
19 changes: 18 additions & 1 deletion test/lazy.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import * as sinon from 'sinon';
import sinonChai from 'sinon-chai';

import { LocationProvider, Router } from '../src/router.js';
import lazy from '../src/lazy.js';
import lazy, { ErrorBoundary } from '../src/lazy.js';

const expect = chai.expect;
chai.use(sinonChai);
Expand Down Expand Up @@ -42,4 +42,21 @@ describe('lazy', () => {
await B.preload();
expect(loadB).to.have.been.calledOnce;
});

it('should forward refs', async () => {
const A = () => <h1>A</h1>;
const LazyA = lazy(() => Promise.resolve(A));

const ref = {};

render(
<ErrorBoundary>
<LazyA ref={ref} />
</ErrorBoundary>,
scratch
);
await new Promise(r => setTimeout(r, 1))

expect(ref.current.constructor).to.equal(A);
});
});
Loading