Skip to content

Commit fcd0328

Browse files
authored
types: Add support for LocationProvider.ctx to support class components (#92)
* fix: Support class components by adding LocationProvider.ctx types * test: Add location context test too
1 parent 784bd04 commit fcd0328

File tree

2 files changed

+32
-7
lines changed

2 files changed

+32
-7
lines changed

src/router.d.ts

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,15 @@
1-
import { AnyComponent, ComponentChildren, FunctionComponent, VNode } from 'preact';
1+
import { AnyComponent, ComponentChildren, Context, FunctionComponent, VNode } from 'preact';
22

3-
export function LocationProvider(props: {
4-
scope?: string | RegExp;
5-
children?: ComponentChildren;
6-
}): VNode;
3+
export const LocationProvider: {
4+
(props: { scope?: string | RegExp; children?: ComponentChildren; }): VNode;
5+
ctx: Context<LocationHook>;
6+
};
77

88
type NestedArray<T> = Array<T | NestedArray<T>>;
99

1010
/**
1111
* Check if a URL path matches against a URL path pattern.
12-
*
12+
*
1313
* Warning: This is an internal API exported only for testing purpose. API could change in future.
1414
* @param url - URL path (e.g. /user/12345)
1515
* @param route - URL pattern (e.g. /user/:id)

test/router.test.js

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { h, Fragment, render, hydrate, options } from 'preact';
1+
import { h, Fragment, render, Component, hydrate, options } from 'preact';
22
import { useState } from 'preact/hooks';
33
import * as chai from 'chai';
44
import * as sinon from 'sinon';
@@ -73,6 +73,31 @@ describe('Router', () => {
7373
});
7474
});
7575

76+
it('should support class components using LocationProvider.ctx', () => {
77+
class Foo extends Component {
78+
static contextType = LocationProvider.ctx;
79+
80+
render() {
81+
loc = this.context;
82+
return <h1>{loc.url}</h1>;
83+
}
84+
}
85+
86+
render(
87+
<LocationProvider>
88+
<Foo />
89+
</LocationProvider>,
90+
scratch
91+
);
92+
93+
expect(scratch).to.have.property('innerHTML', '<h1>/</h1>');
94+
expect(loc).to.deep.include({
95+
url: '/',
96+
path: '/',
97+
query: {},
98+
});
99+
});
100+
76101
it('should allow passing props to a route', async () => {
77102
const Home = sinon.fake(() => <h1>Home</h1>);
78103

0 commit comments

Comments
 (0)