Skip to content

Commit 72dd2b3

Browse files
Add basic support for hooks
1 parent d2d7503 commit 72dd2b3

File tree

2 files changed

+36
-2
lines changed

2 files changed

+36
-2
lines changed

src/index.js

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { encodeEntities, indent, isLargeString, styleObjToCss, assign, getChildren } from './util';
22
import { ENABLE_PRETTY } from '../env';
3+
import { options } from 'preact';
34

45
const SHALLOW = { shallow: true };
56

@@ -59,11 +60,13 @@ function renderToString(vnode, context, opts, inner, isSvgMode) {
5960
nodeName = getComponentName(nodeName);
6061
}
6162
else {
63+
vnode.__c = { __v: vnode };
64+
if (options.render) options.render(vnode);
6265
let rendered;
6366

6467
if (!nodeName.prototype || typeof nodeName.prototype.render!=='function') {
6568
// stateless functional components
66-
rendered = nodeName(props, context);
69+
rendered = nodeName.apply(vnode.__c, props, context);
6770
}
6871
else {
6972
// class-based components

test/render.js

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { render, shallowRender } from '../src';
2-
import { h, Component } from 'preact';
2+
import { h, Component, createContext } from 'preact';
3+
import { useState, useContext } from 'preact/hooks';
34
import chai, { expect } from 'chai';
45
import { spy, stub, match } from 'sinon';
56
import sinonChai from 'sinon-chai';
@@ -606,4 +607,34 @@ describe('render', () => {
606607
expect(Bar).to.have.been.calledOnce.and.calledWithMatch({ count: 1 });
607608
});
608609
});
610+
611+
describe('hooks', () => {
612+
it('should not crash with hooks', () => {
613+
function Foo() {
614+
let [v, setter] = useState(0);
615+
return <button onClick={() => setter(++v)}>count: {v}</button>;
616+
}
617+
618+
// eslint-disable-next-line prefer-arrow-callback
619+
expect(function() {
620+
render(<Foo />);
621+
}).to.not.throw();
622+
});
623+
624+
it('should work with useContext', () => {
625+
let Ctx = createContext('foo');
626+
function Foo() {
627+
let v = useContext(Ctx);
628+
return <div>{v}</div>;
629+
}
630+
631+
let res = render(
632+
<Ctx.Provider value="foo">
633+
<Foo />
634+
</Ctx.Provider>
635+
);
636+
637+
expect(res).to.equal('<div>foo</div>');
638+
});
639+
});
609640
});

0 commit comments

Comments
 (0)