Skip to content

Commit

Permalink
Support contextType on class components
Browse files Browse the repository at this point in the history
  • Loading branch information
sventschui committed Jan 11, 2021
1 parent 658aa5a commit 49ebff5
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 14 deletions.
28 changes: 14 additions & 14 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -57,22 +57,22 @@ export default function prepass(

let isClassComponent = false;

// Necessary for createContext api. Setting this property will pass
// the context value as `this.context` just for this component.
let cxType = nodeName.contextType;
let provider = cxType && context[cxType.__c];
let cctx =
cxType != null
? provider
? provider.props.value
: cxType[createContextDefaultValue] ||
cxType[createContextDefaultValueNew]
: context;

if (
!nodeName.prototype ||
typeof nodeName.prototype.render !== "function"
) {
// Necessary for createContext api. Setting this property will pass
// the context value as `this.context` just for this component.
let cxType = nodeName.contextType;
let provider = cxType && context[cxType.__c];
let cctx =
cxType != null
? provider
? provider.props.value
: cxType[createContextDefaultValue] ||
cxType[createContextDefaultValueNew]
: context;

// stateless functional components
doRender = () => {
try {
Expand All @@ -96,12 +96,12 @@ export default function prepass(

// class-based components
// c = new nodeName(props, context);
c = vnode.__c = new nodeName(props, context);
c = vnode.__c = new nodeName(props, cctx);
// initialize components in dirty state so setState() doesn't enqueue re-rendering:
c.__d = true;
c.__v = vnode;
c.props = props;
c.context = context;
c.context = cctx;
if (c.state === undefined) {
c.state = {};
}
Expand Down
40 changes: 40 additions & 0 deletions src/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -551,6 +551,46 @@ describe("prepass", () => {

expect(renderFn.mock.calls).toEqual([[123]]);
});

it("should support createContext this.context inside classes with defaultValue", async () => {
const ctx = createContext(123);
let ctxValue;

class Inner extends Component {
render() {
ctxValue = this.context;
return null;
}
}

Inner.contextType = ctx;

await prepass(<Inner />);

expect(ctxValue).toEqual(123);
});

it("should support createContext this.context inside classes", async () => {
const ctx = createContext(123);
let ctxValue;

class Inner extends Component {
render() {
ctxValue = this.context;
return null;
}
}

Inner.contextType = ctx;

await prepass(
<ctx.Provider value={456}>
<Inner />
</ctx.Provider>
);

expect(ctxValue).toEqual(456);
});
});

describe("lazy", () => {
Expand Down

0 comments on commit 49ebff5

Please sign in to comment.