From 68cb55f262b75f5d5b723104b830daab37b1ea14 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebastian=20Markb=C3=A5ge?= Date: Thu, 24 Feb 2022 16:31:48 -0500 Subject: [PATCH] Add more warnings for second argument to root.render. (#23358) We already had one for callbacks but containers is also an easy mistake. --- .../src/__tests__/ReactDOMRoot-test.js | 31 +++++++++++++++++++ packages/react-dom/src/client/ReactDOMRoot.js | 11 +++++++ 2 files changed, 42 insertions(+) diff --git a/packages/react-dom/src/__tests__/ReactDOMRoot-test.js b/packages/react-dom/src/__tests__/ReactDOMRoot-test.js index c673423f2b..b39e554e49 100644 --- a/packages/react-dom/src/__tests__/ReactDOMRoot-test.js +++ b/packages/react-dom/src/__tests__/ReactDOMRoot-test.js @@ -51,6 +51,37 @@ describe('ReactDOMRoot', () => { expect(callback).not.toHaveBeenCalled(); }); + it('warn if a container is passed to root.render(...)', async () => { + function App() { + return 'Child'; + } + + const root = ReactDOM.createRoot(container); + expect(() => root.render(, {})).toErrorDev( + 'You passed a second argument to root.render(...) but it only accepts ' + + 'one argument.', + { + withoutStack: true, + }, + ); + }); + + it('warn if a container is passed to root.render(...)', async () => { + function App() { + return 'Child'; + } + + const root = ReactDOM.createRoot(container); + expect(() => root.render(, container)).toErrorDev( + 'You passed a container to the second argument of root.render(...). ' + + "You don't need to pass it again since you already passed it to create " + + 'the root.', + { + withoutStack: true, + }, + ); + }); + it('warns if a callback parameter is provided to unmount', () => { const callback = jest.fn(); const root = ReactDOM.createRoot(container); diff --git a/packages/react-dom/src/client/ReactDOMRoot.js b/packages/react-dom/src/client/ReactDOMRoot.js index 46786fcdea..57bbe7ab96 100644 --- a/packages/react-dom/src/client/ReactDOMRoot.js +++ b/packages/react-dom/src/client/ReactDOMRoot.js @@ -104,7 +104,18 @@ ReactDOMHydrationRoot.prototype.render = ReactDOMRoot.prototype.render = functio 'render(...): does not support the second callback argument. ' + 'To execute a side effect after rendering, declare it in a component body with useEffect().', ); + } else if (isValidContainer(arguments[1])) { + console.error( + 'You passed a container to the second argument of root.render(...). ' + + "You don't need to pass it again since you already passed it to create the root.", + ); + } else if (typeof arguments[1] !== 'undefined') { + console.error( + 'You passed a second argument to root.render(...) but it only accepts ' + + 'one argument.', + ); } + const container = root.containerInfo; if (container.nodeType !== COMMENT_NODE) {