Skip to content

Commit

Permalink
fix: Don't call React.createElement on function as children (lingui#302)
Browse files Browse the repository at this point in the history
Closes lingui#302
  • Loading branch information
tricoder42 authored and Photonios committed Dec 9, 2019
1 parent b0ce89f commit 2327615
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 1 deletion.
12 changes: 12 additions & 0 deletions packages/react/src/I18n.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,18 @@ export default class I18n extends React.Component<*, *> {
...(withHash ? { i18nHash } : {})
}

if (typeof children === "function") {
return children(props)
}

if (process.env.NODE_ENV !== "production") {
console.warn(
"I18n accepts only function as a children. " +
"Other usecases are deprecated and will be removed in v3.0"
)
}

// Deprecate v3.0
return React.isValidElement(children)
? React.cloneElement(children, props)
: React.createElement(children, props)
Expand Down
42 changes: 42 additions & 0 deletions packages/react/src/I18n.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import * as React from "react"
import { mount } from "enzyme"

import { I18n } from "@lingui/react"
import { mockConsole, mockEnv } from "./mocks"

describe("I18n", function() {
const getContext = () => ({
Expand Down Expand Up @@ -29,4 +30,45 @@ describe("I18n", function() {
i18nHash: context.i18nHash
})
})

it("should show deprecation warning for using elements as a children", function() {
expect.assertions(3)

mockConsole(console => {
// Valid
mount(<I18n>{() => <div />}</I18n>)
expect(console.warn).not.toHaveBeenCalledWith(
expect.stringContaining("I18n accepts only function as a children.")
)
})

mockConsole(console => {
// Deprecated!
mount(
<I18n>
<div />
</I18n>
)
expect(console.warn).toHaveBeenCalledWith(
expect.stringContaining("I18n accepts only function as a children.")
)
})

mockEnv("production", () => {
jest.resetModules()
const { I18n } = require("@lingui/react")

// Deprecated, but not warned in production
mockConsole(console => {
mount(
<I18n>
<div />
</I18n>
)
expect(console.warn).not.toHaveBeenCalledWith(
expect.stringContaining("I18n accepts only function as a children.")
)
})
})
})
})
4 changes: 3 additions & 1 deletion packages/react/src/withI18n.js
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,9 @@ const withI18n = (options: withI18nOptions = {}) =>
}
return (
<I18n update={update} withHash={withHash}>
<WrappedComponent {...props} />
{({ i18n, i18nHash }) => (
<WrappedComponent {...props} i18n={i18n} i18nHash={i18nHash} />
)}
</I18n>
)
}
Expand Down

0 comments on commit 2327615

Please sign in to comment.